Understanding the super Keyword and Constructors in Java
When talking about inheritance in Java, it is important to understand that constructors are not inherited by a subclass.
A subclass can, however, invoke a constructor of its super class using the super keyword.
A few points about the super keyword
superis a Java keyword.It can be used to access members of the super class, such as fields and methods.
It can be used to invoke a super class constructor.
When calling a super class constructor using
super(...), it must be the first statement in the subclass constructor.
Example
class SUP { public SUP(String s) { System.out.println("Hi Super: " + s); } } // SUB class extending SUP class class SUB extends SUP { public SUB(String p) { // Explicitly call the super class constructor // super(...) must be the first statement super(p); System.out.println("Hi SUB: " + p); } public static void main(String[] args) { new SUB("Rahul Sharma"); } }
Output
Hi Super: Rahul Sharma Hi SUB: Rahul Sharma
When the SUB object is created, its constructor first invokes the SUP constructor using super(p). After the super class constructor completes, the remaining statements in the SUB constructor are executed.
What happens if super() is not written?
If the super class has an accessible no-argument constructor, Java automatically inserts a call to super() as the first statement of the subclass constructor, provided you don't explicitly call another super class constructor.
For example:
class SUP { public SUP() { System.out.println("Hi Super"); } } class SUB extends SUP { public SUB() { // Compiler automatically inserts super(); System.out.println("Hi SUB"); } }The output is:
Hi Super Hi SUB
However, if the super class does not have an accessible no-argument constructor, the subclass must explicitly invoke one of the available super class constructors.
Important point
Constructors are not inherited in Java. They are invoked as part of object construction.
The super keyword allows a subclass to explicitly invoke a super class constructor and access super class members.
No comments:
Post a Comment