WHAT IS SUPER IN JAVA?

Royce Roy

Total Post:51

Points:255
Posted by  Royce Roy
Java 
 574  View(s)
Ratings:
Rate this:
  1. Mayank Tripathi

    Post:807

    Points:4035
    What is super 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.

    1. 1.super is used to refer immediate parent class instance variable.
    2. 2.super() is used to invoke immediate parent class constructor.
    3. 3.super is used to invoke immediate parent class method
    1)super is used to refer immediate parent class instance variable.
    /example of super keyword  
      
    class Vehicle{  
      int speed=50;  
    }  
      
    class Bike4 extends Vehicle{  
      int speed=100;  
          
      void display(){  
       System.out.println(super.speed);//will print speed of Vehicle now  
      }  
      public static void main(String args[]){  
       Bike4 b=new Bike4();  
       b.display();  
         
    }  

    Output:50 

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

    class Vehicle{  
      Vehicle(){System.out.println("Vehicle is created");}  
    }  
      
    class Bike5 extends Vehicle{  
      Bike5(){  
       super();//will invoke parent class constructor  
       System.out.println("Bike is created");  
      }  
      public static void main(String args[]){  
       Bike5 b=new Bike5();  
            
    }  

    Output:Vehicle is created
              Bike is created 

    3) super is used to invoke immediate parent class method

    class Person{  
    void message(){System.out.println("welcome");}  
    }  
      
    class Student16 extends Person{  
    void message(){System.out.println("welcome to java");}  
      
    void display(){  
    message();//will invoke current class message() method  
    super.message();//will invoke parent class message() method  
    }  
      
    public static void main(String args[]){  
    Student16 s=new Student16();  
    s.display();  
    }  
    }  

    Output:welcome to java
              welcome

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!