Super keyword in Java

In this tutorial we will learn about super keyword in Java. super keyword in java refers to object of Parent class. Super keyword is mainly use to call super class methods or constructor of super class.

Usage of super keyword:

  • The super keyword can be used to use the variable of parent class in child class.
  • The super keyword can be used to call methods of the parent class.
  • The super keyword can be used to invoke the constructor of the parent class.

Example Program:

In this example, how we can use the super keyword to use the variable from the parent class.

class A{  
  int num=10;  
}  
class B extends A{  
  int num=20;  
  public void show(){  
    System.out.println(num); //using num from B class   
    System.out.println(super.num);  //using num from A class   
  }  
}  
public class MyClass{  
   public static void main(String args[]){  
   B obj=new B();  
   obj.show();  
   }
}  

Example Program:

In this example, we will see how we can use the super keyword to the class method of the parent class.

class A{  
  int num=10;  
  public void show(){  
    System.out.println(num);  
  }  
}  
class B extends A{  
  int num=20;  
  public void show(){  
    System.out.println(num);
    super.show(); //calling to show method of A class
  }  
}  
public class MyClass{  
   public static void main(String args[]){  
   B obj=new B();  
   obj.show();  
   }
}  

Example Program:

In this example, we will see how we can use the super keyword to invoke the constructor of the parent class.

class A{    
  public A(int num){  
    System.out.println("This is num "+num);  
  }  
}  
class B extends A{ 
  int num2;    
  public B(int num,int num2){
      super(num);
      this.num2=num2;
  }    
  public void show(){  
     System.out.println("This is Num2 "+num2);  
  }  
}  
public class MyClass{  
   public static void main(String args[]){  
   B obj=new B(10,20);  
   obj.show();  
   }
}  

 

Spread the love
Scroll to Top
×