Java super keyword - The Coding Shala
Home >> Learn Java >> Java Super Keyword
Output:
Output:
Output:
Java super keyword
Like Java this keyword, the super keyword is also a reference variable that is used to refer the parent class objects. When we use inheritance need to use parent class object therefore Java super keyword is used to refer the parent class object.
The following are ways to use the Java super keyword:
- Java super keyword is used to refer to the parent class variables. If a child class and Parent class have the same variables then super can be used to identify the parent class variables. The following example explains it:
class Parent{ int var1 = 10; } class Child extends Parent{ int var1 = 100; void Display() { System.out.println("Child class variable value is: "+var1); System.out.println("Parent class variable value is: "+ super.var1); //access Parent class variable } } class Main{ public static void main(String[] args) { Child c = new Child(); c.Display(); } }
Child class variable value is: 100 Parent class variable value is: 10
- Java super keyword can be used to call parent class methods. The following example explains it:
class Parent{ void msg() { System.out.println("Hello from Parent"); } } class Child extends Parent{ void msg() { System.out.println("Hello from Child"); } void Display() { msg(); super.msg(); } } class Main{ public static void main(String[] args) { Child c = new Child(); c.Display(); } }
Hello from Child Hello from Parent
- Using Java super keyword we can also call parent class constructor. The following example explains it:
class Parent{ Parent(){ System.out.println("Parent class Constructor"); } } class Child extends Parent{ Child(){ super(); System.out.println("Child class Constructor"); } } class Main{ public static void main(String[] args) { Child c = new Child(); } }
Parent class Constructor Child class Constructor
Note: super() must be the first statement in child class constructor.
Other Posts You May Like
Comments
Post a Comment