Java is a powerful object-oriented programming language that supports concepts like inheritance, polymorphism, encapsulation, and abstraction. In this guide, we will learn how a subclass constructor calls a superclass constructor using the super keyword with a complete working example.
📌 What is Inheritance in Java?
Inheritance allows one class to acquire properties and methods of another class. The class being inherited is called the superclass, and the class that inherits is called the subclass.
- Code Reusability
- Better Code Structure
- Supports Polymorphism
🔑 Constructor Chaining using super()
In Java, constructor chaining is achieved using the super() keyword. It is used to call the constructor of the parent class.
- Must be the first statement in constructor
- Used to initialize parent class variables
- Automatically added if not written
🧩 Step 1: Superclass (Person)
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
🧩 Step 2: Subclass (Employee)
public class Employee extends Person {
private String employeeId;
private String department;
public Employee(String name, int age, String employeeId, String department) {
super(name, age);
this.employeeId = employeeId;
this.department = department;
}
@Override
public void display() {
super.display();
System.out.println("Employee ID: " + employeeId);
System.out.println("Department: " + department);
}
}
🧩 Step 3: Main Class
public class Main {
public static void main(String[] args) {
Employee emp = new Employee("John Doe", 30, "E12345", "Engineering");
emp.display();
}
}
🖥️ Output
Name: John Doe Age: 30 Employee ID: E12345 Department: Engineering
🧠Explanation
When an object of Employee is created, the constructor first calls super(name, age), which initializes the parent class variables. Then, the subclass initializes its own variables.
- super() calls parent constructor
- Method overriding extends functionality
- Polymorphism allows flexible behavior
⚠️ Common Mistakes
- Not calling super() when required
- Using super() after other statements
- Incorrect method overriding
💡 Best Practices
- Always call super() if parent has parameters
- Use private variables (encapsulation)
- Follow clean coding standards
📈 Real-World Use Cases
- Banking Systems
- E-commerce Applications
- Employee Management Systems
- Game Development
🔗 Related Java Articles
👉 Final Class in Java Example
👉 User Defined Exception (Divide by Zero)
👉 Thread Synchronization in Java
👉 File Handling in Java
🎯 Conclusion
This article explained how a subclass constructor calls a superclass constructor using the super keyword. Understanding this concept helps you build structured and reusable Java applications.
👉 Bookmark this page for exam preparation and quick revision.

Comments
Post a Comment