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

class Car {
String brand; // instance variable
int year;

void displayInfo() {
System.out.println("Brand: " + brand + ", Year: " + year);
}
}

public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.brand = "Toyota";
car1.year = 2022;
car1.displayInfo();

Car car2 = new Car();
car2.brand = "Honda";
car2.year = 2023;
car2.displayInfo();
}
}

📌 Output:

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

Each object has its own copy of instance variables.


3. Example 2: Class (Static) Variables

class Counter {
static int count = 0; // static variable

Counter() {
count++;
}
}

public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

System.out.println("Total objects created: " + Counter.count);
}
}

📌 Output:

Total objects created: 3

Static variables are shared among all objects of the class.


4. Example 3: Final Variables (Constants)

class Circle {
final double PI = 3.14159; // constant
double radius;

double area() {
return PI * radius * radius;
}
}

public class Main {
public static void main(String[] args) {
Circle c = new Circle();
c.radius = 5;
System.out.println("Area = " + c.area());
}
}

📌 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

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *