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

  1. Instance Variables

    • Belong to an object.

    • Each object has its own copy.

    • Declared without static keyword.

  2. Class Variables (Static Variables)

    • Belong to the class, not the object.

    • Shared by all objects.

    • Declared using static keyword.

  3. Final Variables (Constants)

    • Value cannot be changed after initialization.

    • Declared using final keyword.


2. Example 1: Instance Variables


 

📌 Output:

Brand: Toyota, Year: 2022
Brand: Honda, Year: 2023

Each object has its own copy of instance variables.


3. Example 2: Class (Static) Variables


 

📌 Output:

Total objects created: 3

Static variables are shared among all objects of the class.


4. Example 3: Final Variables (Constants)


 

📌 Output:

Area = 78.53975

❗ Cannot modify PI because 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

You may also like...