Home > DeveloperSection > Interviews > What is super in java?

Posted on    March-28-2015 12:25 AM

 Java Java 
Ratings:
 1 Answer(s)
  386  View(s)
Rate this:

Mayank Tripathi
Mayank Tripathi

Total Post:807

Points:4035
Posted on    March-28-2015 1:18 AM

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


Don't want to miss updates? Please click the below button!

Follow MindStick