1. static
- Purpose: Makes a member (variable or method) belong to the class rather than an instance.
- Usage:
- Static variable: shared across all instances of the class.
- Static method: can be called without creating an object.
- Example:
class Example {
static int count = 0; // shared by all objects
static void showCount() {
System.out.println(count);
}
}
Example.showCount(); // Access without creating object
2. final
- Purpose: Makes a variable, method, or class unchangeable or non-overridable.
- Usage:
- Final variable: value cannot be changed once assigned.
- Final method: cannot be overridden by subclasses.
- Final class: cannot be subclassed.
- Example:
final int MAX = 100; // value cannot change
final class MyClass {} // cannot be extended
class Parent {
final void display() { System.out.println("Hello"); }
}
3. super
- Purpose: Refers to the parent class of the current object.
- Usage:
- Access parent class methods overridden in the child class.
- Access parent class constructor.
- Example:
class Parent {
void show() { System.out.println("Parent"); }
}
class Child extends Parent {
void show() {
super.show(); // call parent method
System.out.println("Child");
}
}
4. this
- Purpose: Refers to the current object.
- Usage:
- Access instance variables when shadowed by method/constructor parameters.
- Call another constructor in the same class.
- Example:
class Example {
int x;
Example(int x) {
this.x = x; // distinguish between instance and parameter
}
void show() {
System.out.println(this.x);
}
}
✅ Quick summary:
Keyword | Meaning |
---|---|
static | Belongs to class, not object |
final | Cannot be changed/overridden/inherited |
super | Refers to parent class |
this | Refers to current object |