Java super keyword & constructors
Consider the following simple example of inheritance, We have created an object of child class -
Contents
Understanding Constructors :
package com.c4learn.inheritance; public class ParentClass { public ParentClass() { System.out.println("Hello Parent"); } public static void main(String[] args) { ChildClass c1 = new ChildClass(); } } class ChildClass extends ParentClass{ public ChildClass() { System.out.println("Hello Child"); } }
Output of the Program :
Hello Parent Hello Child
Explanation of above program :
When you create an instance of a child class, Java automatically calls the default constructor of the parent class before it executes the child class’s constructor. [ Also See - Constructor Example ]
Consider the following code -
package com.c4learn.inheritance; public class ParentClass { public ParentClass() { System.out.println("Hello Parent"); } public ParentClass(int val) { System.out.println("Hello Parameter"); } public static void main(String[] args) { ChildClass c1 = new ChildClass(); } } class ChildClass extends ParentClass{ public ChildClass() { super(5); System.out.println("Hello Child"); } }
Now In the above program, we have written two constructors one with no argument and another with single integer argument.
public ParentClass() { System.out.println("Hello Parent"); } public ParentClass(int val) { System.out.println("Hello Parameter"); }
As we have explicitly called the single argument constructor using the super keyword, Parent Class’s Parameterized Constructor gets called.
Tip #1 : Super Must be First Statement
If you use super to call the parent class constructor, you must put it as first statement in the constructor.
Following is the valid way of calling parent class constructor -
public ChildClass() { super(5); System.out.println("Hello Child"); }
If we write it after other statements then it will throw compile time error -
Tip #2 : Default constructor
If you don’t explicitly call super, the compiler inserts a call to the default constructor of the base class. In that case, the base class must have a default constructor.
If the base class doesn’t have a default constructor, you will get compile time error.