Rabu, 02 April 2025

Static and Non Static Members

| Rabu, 02 April 2025

1.Static Members (Class-Level)

  • Defined using static keyword.
  • Belongs to the class rather than an instance of the class.
  • Shared among all objects of the class.
  • Can be accessed without creating an instance of the class.

Example:

class Example {

static int count = 0; // Static variable
static void displayCount() { // Static method
    System.out.println("Count: " + count);
}

}

public class Main {
public static void main(String[] args) {
Example.count = 5; // Accessing static variable without creating an object
Example.displayCount(); // Calling static method
}
}

Output:

Count: 5

2.Non-Static Members (Instance-Level)

  • Do not use static keyword.
  • Each object of the class gets its own copy.
  • Requires an object to access.

Example:

class Example {
int count = 0; // Non-static variable

void displayCount() { // Non-static method
    System.out.println("Count: " + count);
}

}

public class Main {
public static void main(String[] args) {
Example obj1 = new Example();
Example obj2 = new Example();

    obj1.count = 10;
    obj2.count = 20;

    obj1.displayCount(); // Output: Count: 10
    obj2.displayCount(); // Output: Count: 20
}

}

Output:

Count: 10
Count: 20

When to Use Static?

✅ Use static when the data is shared across all instances (e.g., utility methods, constants).
❌ Avoid static when each object should maintain its own data (e.g., object attributes).

When to Use Non-Static?

✅ When each object should have different values.
✅ When each object should have its own behavior.
✅ When OOP features (Encapsulation, Polymorphism, Inheritance) are needed.
✅ When memory should only be used when an object exists.
❌ When data should be shared among all objects (e.g., static int totalEmployees).
❌ When methods do not depend on object variables (e.g., static int square(int x)).
❌ When memory efficiency matters (e.g., static configurations).
❌ When working with constants (e.g., static final double PI).
❌ When object creation is unnecessary (e.g., utility/helper methods).


Related Posts

Tidak ada komentar:

Posting Komentar