Font Awesome Icons

Tutorial

Java

The super keyword refers to the objects of the immediate parent class. The use of super keyword is given below:

 

  • use of super keyword to access the variables of parent class

 

class Superclass

{   

int num = 100;

 }

class Subclass extends Superclass

{   

int num = 110;   

void printNumber()

{   

System.out.println(super.num);   

}

}    

public class Main3

{   

public static void main(String args[])

Subclass obj= new Subclass(); 

obj.printNumber();    

}

}

 

  • Use of super keyword to invoke the constructor of a parent class

class Shiv

{  

Shiv()

System.out.println(“shiv jee”);  

}  

}  

class Ganesh extends Shiv

{  

 

 

Ganesh()

{  

super();  

System.out.println(“subclass constructor”);  

}  

}  

public class Main5

{  

public static void main(String args[])

{   

Ganesh g=new Ganesh();  

}

}

 

Note: super() is added in each class constructor automatically by the compiler if there is no super()

 

  • super can be used to invoke parent class method

 

class Shiva

{  

void care()

System.out.println(“caring..”); 

}  

}  

class Ganesh extends Shiva

{  

void happy()

System.out.println(“happyness…”); 

}  

void pro()

System.out.println(“spritual…”); 

}  

void work()

{  

 

 

super.care();  

pro();  

}  

}  

public class Main5

{  

public static void main(String args[])

{   

Ganesh g=new Ganesh();  

g.work();  

}

}