Skip to content

super keyword in java

Reading Time: < 1 minute

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.

Usages of super() keyword in java

1.super() is used to refer immediate parent class object.

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

3.super() is used to invoke immediate parent class method.
{code type =java}

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();
}
}

{/code}

Here in this above code super() keyword invokes the variable value of speed as 50 which has been declared in the parent class.So the output for the above code is 50.

super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor as given below:

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();

}

}

See also  Abstraction in java
Tags:

Leave a Reply