Super Keyword
In java super keyword is used to access instance members or constructor of superclass from the subclass. When you override your sub class method with super class method, to call superclass method from subclass use super.overrideMethodName() .
Accessing Instance members of superclass (parent) using super:
Lets see the below example to understand the use of super keyword. We have a class called Parent and it has a child class called Child. We can access the parent class method or variable from the child class by calling
super.member
Here member can be a method or it can also be a variable.
Parent class:
1 2 3 4 5 6 7 |
public class Parent { public int x=5; public void display() { System.out.println("In parent method " +x); } } |
Child class:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class Child extends Parent{ int x=7; public void display() { super.display(); System.out.println(super.x); System.out.println("In child method " +x); } public static void main(String[] args){ Child c = new Child(); c.display(); } } |
Output:
In parent method 5
In child method 7
Use of super in constructor
Lets take a situation where we need to call the constructor of the parent class , Java provide this feature by using the super keyword.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Parent { public Parent() { System.out.println("Parent constructor"); } } public class Child extends Parent { Child(){ super(); System.out.println("Child constructor"); } public static void main(String[] args) { Child c= new Child(); } } |
Output:
Parent constructor
Child constructor
In the above example you can notice that calling the super() from the child class invokes the parent constructor and then executes the remaining statements.
Leave a Reply