Java Class Attributes (Fields / Properties)
🔹 Java Class Attributes (Fields / Properties)
Class attributes are variables declared inside a class but outside any method, constructor, or block. They define the state or properties of an object.
✅ 1. Types of Class Attributes
-
Instance Variables
-
Belong to an object.
-
Each object has its own copy.
-
Declared without
statickeyword.
-
-
Class Variables (Static Variables)
-
Belong to the class, not the object.
-
Shared by all objects.
-
Declared using
statickeyword.
-
-
Final Variables (Constants)
-
Value cannot be changed after initialization.
-
Declared using
finalkeyword.
-
✅ 2. Example 1: Instance Variables
📌 Output:
Each object has its own copy of instance variables.
✅ 3. Example 2: Class (Static) Variables
📌 Output:
Static variables are shared among all objects of the class.
✅ 4. Example 3: Final Variables (Constants)
📌 Output:
❗ Cannot modify
PIbecause it is final.
✅ 5. Key Points
| Attribute Type | Belongs To | Shared Across Objects? | Modifiable? |
|---|---|---|---|
| Instance | Object | No | Yes |
| Static | Class | Yes | Yes |
| Final | Object/Class | Depends (with static) | No |
-
Instance variables → Object-specific data
-
Static variables → Class-wide shared data
-
Final variables → Constants that cannot change
