Learn how to use the super and final keywords in Java with clear examples, use cases, and best practices. Understand how these keywords improve inheritance, method overriding, and code safety in Java applications.
Using super and final Keywords in Java: Complete Guide with Examples
In Java programming, the super and final keywords are two essential tools that empower developers to manage inheritance, control method overriding, and enhance code safety. Whether you’re a beginner or an experienced programmer, mastering these keywords is key to writing clean, efficient, and maintainable Java code.
This comprehensive guide will explain the concept, syntax, use cases, and best practices for using the super and final keywords, with real-world examples and detailed explanations.
What Are super and final Keywords in Java?
In Java, keywords are reserved words with special meanings. Among them, super and final are particularly important in Object-Oriented Programming (OOP) because they deal with inheritance and immutability.
| Keyword | Purpose | Used With |
|---|---|---|
super | Refers to the superclass (parent class) and is used to access its members or constructors. | Classes, methods, constructors |
final | Restricts modification — can prevent class inheritance, method overriding, or variable reassignment. | Variables, methods, classes |
Understanding the super Keyword in Java
The super keyword in Java is used when working with inheritance. It allows a subclass to access members (methods or variables) of its immediate superclass.
Key Uses of super:
- To access superclass variables when they are hidden by subclass variables.
- To call superclass methods when they are overridden in the subclass.
- To invoke superclass constructors explicitly.
1. Accessing Superclass Members
If a subclass defines a variable or method with the same name as in its superclass, the subclass version hides the superclass version. The super keyword helps you access the hidden member.
Example:
class Animal {
String type = "Animal";
}
class Dog extends Animal {
String type = "Dog";
void displayType() {
System.out.println("This is a " + type); // Dog
System.out.println("Superclass type: " + super.type); // Animal
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.displayType();
}
}Output:
This is a Dog
Superclass type: AnimalHere, super.type accesses the type variable from the superclass.
2. Calling Superclass Methods
The super keyword can also be used to invoke a superclass method that has been overridden by the subclass.
Example:
class Vehicle {
void start() {
System.out.println("Vehicle is starting...");
}
}
class Car extends Vehicle {
void start() {
System.out.println("Car is starting...");
}
void display() {
super.start(); // Call parent class method
start(); // Call child class method
}
}
public class Demo {
public static void main(String[] args) {
Car c = new Car();
c.display();
}
}Output:
Vehicle is starting...
Car is starting...super.start() calls the method from the superclass Vehicle.
3. Invoking Superclass Constructor
A common use of super is to invoke a constructor from the superclass, especially when the superclass has a parameterized constructor.
Example:
class Person {
Person(String name) {
System.out.println("Name: " + name);
}
}
class Student extends Person {
Student(String name) {
super(name); // Call superclass constructor
System.out.println("Student constructor called.");
}
}
public class Test {
public static void main(String[] args) {
Student s = new Student("Emma");
}
}Output:
Name: Emma
Student constructor called.Using super() ensures that the parent class is initialized properly before the subclass.
Understanding the final Keyword in Java
The final keyword in Java is used to impose restrictions. It can be applied to variables, methods, and classes, ensuring that they cannot be changed or overridden.
1. final Variables
A final variable is a constant whose value cannot be changed once assigned.
Example:
class Circle {
final double PI = 3.14159;
void display() {
System.out.println("Value of PI: " + PI);
}
}If you try to modify PI, Java will throw a compile-time error.
Best Practice:
Use uppercase letters for final constants, e.g., MAX_SPEED, PI.
2. final Methods
A final method cannot be overridden by subclasses. This is useful when you want to prevent modification of critical methods.
Example:
class Animal {
final void sound() {
System.out.println("Animals make sound.");
}
}
class Dog extends Animal {
// Error: Cannot override the final method from Animal
// void sound() { System.out.println("Dog barks."); }
}Here, the sound() method is final, so the subclass Dog cannot override it.
3. final Classes
A final class cannot be extended (inherited). This is often used for security and design purposes, especially in immutable classes like String.
Example:
final class Vehicle {
void display() {
System.out.println("This is a vehicle.");
}
}
// Error: Cannot inherit from final Vehicle
// class Car extends Vehicle { }Real-World Example:java.lang.String is a final class — you cannot extend it.
Difference Between super and final in Java
| Feature | super Keyword | final Keyword |
|---|---|---|
| Purpose | Access superclass members | Restrict inheritance, modification, or overriding |
| Used With | Methods, variables, constructors | Classes, methods, variables |
| Effect on Inheritance | Enables interaction with superclass | Restricts inheritance |
| Common Use Case | Call superclass constructor or method | Make class immutable or prevent changes |
Best Practices for Using super and final
- Always call
super()explicitly in subclass constructors when the superclass requires arguments. - Use
finalfor constants and configuration values that shouldn’t change. - Avoid overusing
finalon methods unless necessary—it limits flexibility. - Prefer composition over inheritance when possible.
- Use
supercarefully to maintain clarity between superclass and subclass responsibilities.
Conclusion
The super and final keywords in Java are small but powerful tools that shape how inheritance and immutability work in your code.
While super enhances interaction between subclasses and superclasses, final provides control and safety by preventing unwanted modifications.
By mastering these two keywords, developers can write more robust, predictable, and maintainable Java programs that follow best OOP practices.
FAQs: Using super and final in Java
1. Can I use super in a static method?
No. The super keyword cannot be used in static contexts because it refers to an instance of a superclass.
2. Can a class be both final and abstract?
No. A final class cannot be subclassed, while an abstract class must be subclassed—making them mutually exclusive.
3. Can we override a final method?
No. A final method cannot be overridden by a subclass.
4. Is it mandatory to call super() in every constructor?
Not always. If the superclass has a no-argument constructor, the compiler automatically inserts super().
5. Why is String class final in Java?
The String class is final to ensure immutability, security, and better performance when used in applications.
