Web
Analytics
Super KeyWord in Java | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Super KeyWord in Java

Super:– Super keyword  is used to

  • Call the Super class variable.
  •  Call the super class constructor.
  • Call the super class methods.

1. Call the Super class variable :

Its mandatory to use when derived class variables and base class variables names are same.

Example

 

class Test1 
{ 
 int a=10;
  int b=20;
 }; 
class Test extends Test1
 {  
int a=100; 
 int b=200;
  void add(int a,int b) 
 {   
System.out.println(a+b); 
 
 System.out.println(this.a+this.b); 
 
 System.out.println(super.a+super.b);   
  }  
public static void main(String[] args) 
 {  
 Test t=new Test();  
 t.add(1000,2000); 
 } }; 

2.Call the super class constructor

  •  inside the constructors super keyword must be first statement of the constructor otherwise the compiler raise compilation error.
  • Super class constructor can be called only once in child class constructor or in method.

Example

 

class Test1 
{  
Test1(int i,int j) 
 {  
 System.out.println(i);
   System.out.println(j);
 System.out.println("two arg constructor");
  }
 }; 
class Test extends Test1
  {  
Test(int i)
  {  
 super(100,200); 
System.out.println("int -arg constructor"); 
   
 }  
public static void main(String[] args) 
  {  
 Test t=new Test(10);
 }
 } 

3.Call the super class methods

Its mandatory to use when derived class methods and base class methods names are same.

Example

class Parent
 {  
void m1() 
 {
 System.out.println("parent class method"); 
 } 
}; 
class Child extends Parent
 {  
void m1() 
 { 
System.out.println("child class method"); 
 }  
void m2() 
 {  
 this.m1();
 System.out.println("child class method"); 
  super.m1(); 
 }  
public static void main(String[] arhs)  { 
  Child c=new Child();  
 c.m2();  
} 
};