Table of Contents

    Properties / Attributes

    Chapter 16.4

    Properties / Attributes in Object-Oriented Programming

    Learn what properties and attributes are in Object-Oriented Programming, how they store object data, how they describe object state, and how they are used with classes, objects, methods, and constructors.

    Introduction

    In Object-Oriented Programming, properties or attributes are used to store information about an object. They describe the characteristics, data, or state of an object. Every object usually has some data that makes it meaningful, and this data is stored using properties or attributes.

    For example, if we have a Student object, it may have attributes such as name, roll number, age, course, marks, and grade. If we have a Car object, it may have attributes such as brand, model, color, speed, and fuel level.

    Properties are important because they allow each object to store its own values. Two objects created from the same class can have the same structure but different property values.

    "Properties or attributes are variables inside a class or object that store the data or state of that object."

    Simple Definition of Properties / Attributes

    A property or attribute is a data member of a class or object. It represents a piece of information related to that object.

    In simple words:

    • Properties store object data.
    • Attributes describe object characteristics.
    • They define the state of an object.
    • They are usually declared inside a class.
    • Each object can have its own values for these properties.
    BASIC IDEA
    Object State = Property Values

    For example, a student object may have the following state:

    
    name = "Rahul"
    rollNumber = 101
    marks = 85
    grade = "B"
    

    These values describe the current state of the student object.

    Important: Properties and attributes are often used to mean the same thing. Some languages use the word field, some use attribute, and some use property. The core concept is the same: they store object data.

    Properties as Object State

    In Object-Oriented Programming, every object usually has three main characteristics: state, behavior, and identity. Properties are directly related to the state of an object.

    The state of an object means the current values stored inside the object. These values can change during program execution depending on the operations performed on the object.

    Student Object State

    A student object may store name, roll number, course, marks, and grade. These stored values represent the current state of that student object.

    Object Properties / Attributes Example Values
    Student name, rollNumber, marks, grade Rahul, 101, 85, B
    Car brand, color, speed, fuelLevel Toyota, Red, 60, 40%
    Book title, author, price, isbn Programming Basics, R. Sharma, 499, ISBN123
    Bank Account accountNumber, holderName, balance A101, Ayesha, 5000
    Product productId, name, price, stock P101, Keyboard, 1200, 50

    Different Names Used for Properties

    Different programming languages and books may use different terms for properties or attributes. Beginners should not get confused by these names. They usually refer to data stored inside a class or object.

    Term Meaning Common Usage
    Property Data associated with an object, often accessed with controlled get/set behavior. Common in C#, JavaScript, TypeScript, and general OOP discussions.
    Attribute A characteristic or data value of an object. Common in Python and general OOP theory.
    Field A variable declared inside a class. Common in Java and C#.
    Data Member A member of a class that stores data. Common in C++ and traditional OOP terminology.
    Instance Variable A variable that belongs to a specific object instance. Common in Java and object-oriented design.
    Beginner Tip: If you hear property, attribute, field, data member, or instance variable, first understand the context. In many beginner-level lessons, these terms refer to object data.

    Properties Inside a Class

    A class defines what properties its objects will have. The class acts as a blueprint, and properties are part of that blueprint. When an object is created from the class, the object gets its own values for those properties.

    
    // Conceptual class with properties
    
    Class Student
    {
        name
        rollNumber
        course
        marks
    }
    

    In the above conceptual example, name, rollNumber, course, and marks are properties of the Student class. Objects created from this class can store actual values for these properties.

    CLASS AND PROPERTIES
    Class defines Properties   |   Object stores Values

    Example: Student Properties

    Let us understand properties with a student example. A student can have different details such as name, roll number, course, marks, and grade. These details are represented as properties.

    Property Name Meaning Example Value Possible Data Type
    name Stores the student's name. Rahul String / Text
    rollNumber Stores the student's roll number. 101 Integer / Number
    course Stores the course name. Programming Fundamentals String / Text
    marks Stores the student's marks. 85 Integer / Number
    grade Stores the final grade. B Character / String

    Basic Syntax Concept

    The syntax for declaring properties changes from language to language. However, the general idea is that properties are declared inside a class and later accessed through an object.

    
    // General conceptual syntax
    
    Class ClassName
    {
        dataType propertyName
    }
    

    For example:

    
    // Conceptual example
    
    Class Student
    {
        String name
        int rollNumber
        int marks
    }
    

    Here, name, rollNumber, and marks are properties. Each property has a name and a type of value it can store.

    Java Example of Properties

    The following Java example shows properties declared inside a class and then used by an object.

    Prerequisites: To understand this example, you should know basic variables, data types, classes, objects, the dot operator, and the main method in Java.
    
    class Student {
    
        // Properties / Fields
        String name;
        int rollNumber;
        int marks;
    
        void displayDetails() {
            System.out.println("Name: " + name);
            System.out.println("Roll Number: " + rollNumber);
            System.out.println("Marks: " + marks);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            Student student1 = new Student();
    
            student1.name = "Rahul";
            student1.rollNumber = 101;
            student1.marks = 85;
    
            student1.displayDetails();
        }
    }
    

    In this example, name, rollNumber, and marks are properties of the Student class. The object student1 stores actual values for those properties.

    JavaScript Example of Properties

    In JavaScript, properties can be assigned to an object using the constructor or directly using the dot operator. The following example uses a class and constructor.

    Prerequisites: To understand this example, you should know JavaScript variables, classes, constructors, objects, methods, and console output.
    
    class Student {
    
        constructor(name, rollNumber, marks) {
            this.name = name;
            this.rollNumber = rollNumber;
            this.marks = marks;
        }
    
        displayDetails() {
            console.log("Name: " + this.name);
            console.log("Roll Number: " + this.rollNumber);
            console.log("Marks: " + this.marks);
        }
    }
    
    const student1 = new Student("Ayesha", 102, 92);
    
    student1.displayDetails();
    

    In this example, name, rollNumber, and marks are properties of the student object. The keyword this refers to the current object.

    Accessing Properties Using Dot Operator

    In many programming languages, object properties are accessed using the dot operator. The dot operator connects the object name with the property name.

    DOT OPERATOR
    objectName.propertyName
    
    // Accessing and changing property values
    
    student1.name = "Rahul";
    student1.marks = 85;
    
    System.out.println(student1.name);
    System.out.println(student1.marks);
    

    Here, student1.name accesses the name property of the student1 object. student1.marks accesses the marks property of the same object.

    Same Properties, Different Object Values

    One class can create many objects. Each object has the same property names, but the values can be different. This is one of the main advantages of using properties inside classes.

    
    Student student1 = new Student();
    student1.name = "Rahul";
    student1.rollNumber = 101;
    student1.marks = 85;
    
    Student student2 = new Student();
    student2.name = "Ayesha";
    student2.rollNumber = 102;
    student2.marks = 92;
    

    Both student1 and student2 are created from the same Student class. However, each object stores its own separate property values.

    Object name rollNumber marks
    student1 Rahul 101 85
    student2 Ayesha 102 92
    student3 John 103 76

    Types of Properties / Attributes

    Properties can be classified in different ways depending on how they are used. The most common categories are instance properties, class or static properties, read-only properties, and calculated properties.

    1

    Instance Properties

    Properties that belong to individual objects

    Instance properties are stored separately for each object. If two objects are created from the same class, each object has its own values for instance properties.

    Example student1.name and student2.name can store different names.
    2

    Class / Static Properties

    Properties shared by the class rather than individual objects

    A static property belongs to the class itself. It is shared among all objects of that class. Static properties are useful for values that should be common for all objects.

    Example A schoolName property may be common for all student objects.
    3

    Read-Only Properties

    Properties that can be read but should not be changed directly

    Some properties should not be changed after initialization. These are often treated as read-only values. For example, an account number should not change frequently after a bank account is created.

    Example accountNumber may be assigned once and then protected from direct modification.
    4

    Calculated Properties

    Values derived from other properties

    A calculated property is not always stored directly. It may be calculated using other property values. For example, total price can be calculated from price and quantity.

    Example totalAmount = price × quantity

    Instance Property vs Static Property

    Beginners should clearly understand the difference between instance properties and static properties. Instance properties belong to individual objects, while static properties belong to the class.

    Basis Instance Property Static Property
    Belongs To Individual object Class itself
    Memory Each object usually has its own copy Shared by all objects
    Value Can be different for each object Usually common for all objects
    Example student1.name, student2.name Student.schoolName
    Use Case Object-specific data Common data or counters

    Static Property Example

    Suppose all students belong to the same school. Instead of storing the same school name separately for every object, we can use a static property.

    
    class Student {
    
        String name;
        int rollNumber;
    
        static String schoolName = "ABC Public School";
    
        void displayDetails() {
            System.out.println("Name: " + name);
            System.out.println("Roll Number: " + rollNumber);
            System.out.println("School: " + schoolName);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            Student student1 = new Student();
            student1.name = "Rahul";
            student1.rollNumber = 101;
    
            Student student2 = new Student();
            student2.name = "Ayesha";
            student2.rollNumber = 102;
    
            student1.displayDetails();
            student2.displayDetails();
        }
    }
    

    In this example, name and rollNumber are instance properties, while schoolName is a static property shared by all Student objects.

    Access Modifiers and Properties

    Properties should not always be directly accessible from outside the class. Some data should be protected to prevent incorrect or unsafe modification. Access modifiers help control how properties can be accessed.

    Access Modifier Meaning Example Use
    public Can be accessed from outside the class. Useful for simple data or methods meant for external access.
    private Can be accessed only inside the class. Useful for sensitive data such as balance or password hash.
    protected Can be accessed inside the class and related child classes. Useful when inheritance is involved.

    Poor Property Design

    • All properties are public without control.
    • Important data can be changed directly.
    • No validation before updating values.
    • Object state can become invalid.
    • Security and reliability may be reduced.

    Better Property Design

    • Sensitive properties are kept private.
    • Methods are used to update important values.
    • Validation is applied before changes.
    • Object state remains controlled.
    • Encapsulation becomes stronger.

    Properties and Encapsulation

    Encapsulation means wrapping data and methods together and controlling access to that data. Properties are often protected using encapsulation so that they cannot be changed directly in an unsafe way.

    For example, in a bank account object, the balance property should not be changed directly. If anyone can directly modify balance, the account may become invalid. Instead, balance should be updated using methods such as deposit() and withdraw().

    
    class BankAccount {
    
        private double balance;
    
        void deposit(double amount) {
            if (amount > 0) {
                balance = balance + amount;
            }
        }
    
        void withdraw(double amount) {
            if (amount > 0 && amount <= balance) {
                balance = balance - amount;
            } else {
                System.out.println("Invalid withdrawal amount");
            }
        }
    
        double getBalance() {
            return balance;
        }
    }
    

    In this example, balance is private. It cannot be changed directly from outside the class. The methods deposit() and withdraw() control how the balance is updated.

    Getters and Setters

    Getters and setters are methods used to read and update private properties safely. A getter returns the value of a property, while a setter updates the value after applying necessary rules or validation.

    GETTER AND SETTER
    Getter reads Property   |   Setter updates Property
    
    class Student {
    
        private String name;
        private int marks;
    
        String getName() {
            return name;
        }
    
        void setName(String studentName) {
            name = studentName;
        }
    
        int getMarks() {
            return marks;
        }
    
        void setMarks(int studentMarks) {
            if (studentMarks >= 0 && studentMarks <= 100) {
                marks = studentMarks;
            } else {
                System.out.println("Invalid marks");
            }
        }
    }
    

    In this example, name and marks are private properties. The setter for marks checks that the value is between 0 and 100 before storing it.

    Important: Getters and setters are not only for reading and writing data. They also help validate, protect, and control object state.

    Initializing Properties

    Property initialization means giving initial values to properties when an object is created. If properties are not initialized properly, the object may contain empty, default, or invalid values.

    Properties can be initialized in different ways:

    • Directly when declaring the property.
    • Using a constructor.
    • Using setter methods.
    • Using object initialization syntax, depending on the language.

    Constructor-Based Initialization

    
    class Student {
    
        String name;
        int rollNumber;
        int marks;
    
        Student(String studentName, int studentRollNumber, int studentMarks) {
            name = studentName;
            rollNumber = studentRollNumber;
            marks = studentMarks;
        }
    
        void displayDetails() {
            System.out.println(name);
            System.out.println(rollNumber);
            System.out.println(marks);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            Student student1 = new Student("Rahul", 101, 85);
    
            student1.displayDetails();
        }
    }
    

    Here, the constructor receives values and assigns them to the object's properties when the object is created.

    Calculated Properties

    Sometimes a value does not need to be stored separately because it can be calculated from other properties. Such values are known as calculated or derived properties.

    For example, in a Product object, total price can be calculated using price and quantity.

    CALCULATED PROPERTY
    Total Price = Price × Quantity
    
    class Product {
    
        double price;
        int quantity;
    
        double getTotalPrice() {
            return price * quantity;
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            Product product1 = new Product();
    
            product1.price = 500;
            product1.quantity = 3;
    
            System.out.println("Total Price: " + product1.getTotalPrice());
        }
    }
    

    In this example, total price is not stored separately. It is calculated whenever needed using price and quantity.

    Real-World Example: Bank Account Properties

    A BankAccount class contains properties that describe account information. Some properties should be public or readable, while others should be protected.

    Property Meaning Should It Be Directly Changeable?
    accountNumber Unique number of the account. No, usually it should be protected after creation.
    accountHolderName Name of the account holder. Maybe, through controlled update process.
    balance Current amount available in the account. No, it should be changed through deposit or withdraw methods.
    accountType Type of account such as savings or current. Usually controlled by business rules.

    Real-World Example: Product Properties

    In an online shopping application, a Product class may contain properties such as product ID, name, price, category, stock quantity, and discount.

    
    class Product {
    
        String productId;
        String productName;
        double price;
        int stockQuantity;
        String category;
    
        void displayProduct() {
            System.out.println("Product ID: " + productId);
            System.out.println("Name: " + productName);
            System.out.println("Price: " + price);
            System.out.println("Stock: " + stockQuantity);
            System.out.println("Category: " + category);
        }
    }
    

    These properties describe the current details of a product object. Different product objects can have different values.

    Characteristics of Good Properties

    A well-designed property should clearly represent one piece of data related to an object. It should be meaningful, valid, and placed in the correct class.

    Good Property Design Principles

    • Use meaningful property names.
    • Store only data that belongs to the object.
    • Choose proper data types for properties.
    • Keep sensitive properties private when needed.
    • Use validation before updating important values.
    • Do not duplicate data unnecessarily.
    • Use calculated properties when values can be derived.
    • Initialize required properties properly.
    • Keep property names consistent across the project.
    • Avoid vague property names such as data, value, item, or info without clear context.

    Naming Rules for Properties

    Property names should be clear and descriptive. A good property name helps other developers understand what data is stored inside the object.

    Poor Property Name Better Property Name Reason
    n name name is clearer than n.
    rn rollNumber rollNumber clearly describes the student roll number.
    p price price is easier to understand.
    qty quantity quantity is more readable for beginners.
    bal balance balance clearly represents account balance.

    Property Naming Best Practices

    • Use meaningful names such as studentName, productPrice, accountBalance.
    • Use camelCase in languages where it is commonly followed.
    • Avoid names that are too short or unclear.
    • Avoid using spaces in property names.
    • Avoid special characters in property names unless the language allows and requires them.
    • Use nouns or noun phrases because properties represent data.
    • Keep naming style consistent throughout the project.

    Property vs Method

    Properties and methods are both members of a class, but they have different purposes. Properties store data, while methods perform actions or operations.

    Basis Property / Attribute Method
    Purpose Stores data or state. Performs an action or behavior.
    Represents Characteristics of an object. Actions of an object.
    Example name, marks, balance, price displayDetails(), deposit(), calculateTotal()
    Syntax Style Usually used like a variable. Usually called like a function.
    Question Answered What does the object have? What can the object do?

    Property vs Variable

    A property is a kind of variable, but it belongs to a class or object. A normal variable may exist inside a method or block, while a property describes object data.

    Basis Normal Variable Property / Attribute
    Location Usually declared inside a method, function, or block. Declared inside a class or object.
    Purpose Stores temporary or local data. Stores object state.
    Lifetime May exist only while the method runs. Usually exists as long as the object exists.
    Example totalMarks inside calculateGrade() marks inside Student object

    Common Mistakes Beginners Make

    While learning properties and attributes, beginners often make some common mistakes. Understanding these mistakes helps in writing cleaner and safer object-oriented code.

    Common Mistakes

    • Confusing properties with methods.
    • Using unclear property names such as x, y, data, or value.
    • Making all properties public without thinking about security.
    • Not initializing required properties.
    • Using wrong data types for properties.
    • Duplicating the same data in multiple properties.
    • Allowing invalid values such as negative marks or negative balance.
    • Putting unrelated properties inside the wrong class.

    Better Approach

    • Use properties only for object data.
    • Use methods for object actions.
    • Use meaningful and descriptive property names.
    • Keep sensitive properties private.
    • Use constructors or setters to initialize values.
    • Validate values before assigning them.
    • Use calculated properties when suitable.
    • Keep each property relevant to its class.

    How to Identify Properties from a Problem Statement

    When designing a class, you can identify properties by asking what information needs to be stored about an object. Properties usually come from descriptive details in the problem statement.

    PROPERTY IDENTIFICATION RULE
    Object Details become Properties

    Consider this problem statement:

    "A library system stores book title, author, ISBN, price, category, and availability status."

    From this statement, possible properties for a Book class are:

    • title
    • author
    • isbn
    • price
    • category
    • isAvailable

    Mini Practice Activity

    Try to identify properties from the following scenarios. This exercise will help you think like an object-oriented programmer.

    Scenario Class Possible Properties / Attributes
    School Management Student studentId, name, rollNumber, course, marks, grade
    Banking System BankAccount accountNumber, holderName, balance, accountType
    Library System Book bookId, title, author, isbn, availability
    Online Shopping Product productId, productName, price, stockQuantity, category
    Hospital System Patient patientId, name, age, disease, contactNumber
    Transport System Vehicle vehicleNumber, brand, model, speed, fuelLevel

    Frequently Asked Questions

    1. What are properties in OOP?

    Properties are data members of a class or object. They store information about an object, such as name, age, price, marks, or balance.

    2. Are properties and attributes the same?

    In many beginner-level discussions, properties and attributes mean the same thing. Both refer to data that describes an object. However, some programming languages may define these terms more specifically.

    3. What is the difference between a property and a method?

    A property stores data, while a method performs an action. For example, marks is a property, and calculateGrade() is a method.

    4. Can different objects have different property values?

    Yes. Objects created from the same class can have the same property names but different values. For example, student1.name may be Rahul, while student2.name may be Ayesha.

    5. Why should some properties be private?

    Some properties should be private to protect object data from incorrect modification. For example, a bank account balance should be updated only through deposit and withdraw methods.

    6. What is an instance property?

    An instance property belongs to a specific object. Each object has its own value for that property. For example, each student object can have a different name and marks.

    7. What is a static property?

    A static property belongs to the class itself and is usually shared by all objects of that class. For example, schoolName may be common for all Student objects.

    8. What is a calculated property?

    A calculated property is a value derived from other properties. For example, total price can be calculated using price and quantity.

    Summary

    Properties or attributes are essential parts of Object-Oriented Programming. They store the data or state of an object. Without properties, objects would not have meaningful information.

    A class defines the properties that its objects will have, and each object stores its own values for those properties. For example, a Student class may define name, roll number, and marks, while each student object stores different values for these properties.

    Good property design is important for creating clean, safe, and maintainable programs. Properties should have meaningful names, correct data types, proper initialization, and suitable access control. Sensitive properties should be protected using encapsulation, and methods should be used to update them safely when needed.

    Key Takeaway

    Properties or attributes are variables inside a class or object that store object data. They describe the state of an object. A class defines properties, and each object stores its own values for those properties.