Java super keyword - The Coding Shala

Home >> Learn Java >> Java Super Keyword

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();
 }
}
Output: 
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();
 }
}
Output: 
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();
 }
}
Output: 

Parent class Constructor
Child class Constructor

Note: super() must be the first statement in child class constructor. 


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Anti Diagonals - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

LeetCode - Bulb Switcher Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala