What is Super Keyword?
The super keyword in Java is used to refer to the immediate parent class object. It helps access parent class variables, methods, or constructors that are hidden by child class members.
Example 1: Accessing Parent Variable using super
class Animal {
String color = "White";
}
class Dog extends Animal {
String color = "Black";
void printColor() {
System.out.println("Child color: " + color);
System.out.println("Parent color: " + super.color);
}
}
class TestSuper {
public static void main(String args[]) {
Dog d = new Dog();
d.printColor();
}
}
Output:
Child color: Black Parent color: White
Example 2: Calling Parent Method using super
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void eat() {
System.out.println("Dog is eating");
}
void bark() {
super.eat(); // Calling parent method
System.out.println("Dog is barking");
}
}
class TestSuperMethod {
public static void main(String args[]) {
Dog d = new Dog();
d.bark();
}
}
Output:
Animal is eating Dog is barking
What is Final Keyword?
The final keyword in Java is used to restrict modification. Once a variable, method, or class is declared final, it cannot be changed, overridden, or inherited respectively.
Example 1: Final Variable
class Example {
final int speed = 100;
void run() {
// speed = 200; // ❌ Error: cannot assign value to final variable
System.out.println("Speed: " + speed);
}
public static void main(String[] args) {
new Example().run();
}
}
Output:
Speed: 100
Example 2: Final Class and Method
final class Vehicle {
final void run() {
System.out.println("Running safely...");
}
}
// class Car extends Vehicle { } // ❌ Error: cannot inherit from final class
public class TestFinal {
public static void main(String args[]) {
Vehicle v = new Vehicle();
v.run();
}
}
Output:
Running safely...
Difference Between Super and Final Keyword
super is used for parent reference access, while final is used to prevent inheritance, overriding, or reassigning. Super supports parent-child relationships; final enforces immutability.
Example:
class Parent {
final int number = 50;
void display() {
System.out.println("Parent display");
}
}
class Child extends Parent {
void show() {
System.out.println("Accessing parent variable: " + super.number);
super.display();
}
}
public class SuperFinalDemo {
public static void main(String[] args) {
Child obj = new Child();
obj.show();
}
}
Output:
Accessing parent variable: 50 Parent display
Best Practices
Use super for clear parent access only when necessary
Use final for creating constants and preventing modification of sensitive data
Avoid overusing final unless the design demands strict immutability
Always maintain proper naming and documentation when using these keywords