Followers

coreJava: super keyword in java

super keyword in java

The super keyword in java is a reference variable that is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.

Usage of java super Keyword


  • super is used to refer immediate parent class instance variable.
  • super() is used to invoke immediate parent class constructor.
  • super is used to invoke immediate parent class method.

super is used to refer immediate parent class instance variable.

package com.super1; 
class Employee1 {
String name = "Employee1";

public class Programmer1 extends Employee1 {
       String name = "Programmer1";
       void display(){
              System.out.println(name);
              System.out.println(super.name);
       }

       public static void main(String[] args) {             
              Programmer1 pr1 = new Programmer1();
              pr1.display();            

       } 

}

super() is used to invoke immediate parent class constructor.

As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement.If you are creating your own constructor and you don't have either this() or super() as the first statement, compiler will provide super() as the first statement of the constructor.

package com.super1;
class Employee2 {
       Employee2(){
              System.out.println("Employee2 constructor...");
       } 

public class Programmer2 extends Employee2 {
       Programmer2(){
              super();//will invoke parent class constructor 
              System.out.println("Programmer2 constructor...");             
       }
       public static void main(String[] args) {             
              Programmer2 pr2 = new Programmer2();           
       }

super is used to invoke immediate parent class method.

The super keyword can also be used to invoke parent class method. It should be used in case subclass contains the same method as parent class as in the example given below:

package com.super1; 
class Employee3 {
       void message(){System.out.println("welcome from Employer3");}  
}
public class Programmer3 extends Employee3 {
       void message(){
              System.out.println("welcome from Programmer3");             
       }
       void display(){
              message();
              super.message();             
       }      
       public static void main(String[] args) {             
              Programmer3 pr3 = new Programmer3();
              pr3.display();             
       }
       }

No comments:

Post a Comment