Constructor Method in Inheritance in Java
Constructor Method in Inheritance in Java
In Java, when a class is inherited (i.e., when a subclass extends a superclass), the constructor
of the superclass is not inherited by the subclass, but it is called when an object of the
subclass is created.
This ensures that the superclass is properly initialized before the subclass-specific attributes
and methods are executed.
Key Points:
Examples
1. Using Default Constructor
class Parent {
Parent() {
System.out.println("Parent class constructor");
}
}
Output:
👉 The superclass constructor (Parent()) is called before the subclass constructor (Child()).
If the superclass has a parameterized constructor, the subclass must explicitly call it.
class Parent {
Parent(String msg) {
System.out.println("Parent constructor: " + msg);
}
}
Output:
Parent constructor: Hello!
Child constructor: Hello!
class Parent {
Parent() {
System.out.println("Parent default constructor");
}
Parent(int x) {
System.out.println("Parent parameterized constructor:
" + x);
}
}
Output:
Parent parameterized constructor: 10
Child default constructor
Key Takeaways
1. Constructors are not inherited but are called during object creation.
2. super() is used to call the superclass constructor explicitly.
3. If the superclass has a parameterized constructor, the subclass must call it
explicitly.