The super and final keywords in Java are essential tools for inheritance and data protection. They help manage class relationships and prevent unwanted modifications in Object-Oriented Programming.
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.
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
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
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.
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
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...
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
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.