super keyword in Java

super keyword is used to refer the parent class or super class.

This cannot be applied without inheriting a class.

super keyword can be used for referencing

  • variables of parent class
  • methods of parent class
  • Constructor of parent class.

super keyword for referencing variables of parent class

Example

class Vehicle{

int avgspeed=100;

}

class CarSuper extends Vehicle{

void averagespeed(){

System.out.println("Average speed of a car is "+super.avgspeed);

}

public static void main(String args[]){

CarSuper benz=new CarSuper();

benz.averagespeed();

}

}

Try In Editor

Output

Average speed of a car is 100


super keyword for parent class methods

Example

class Shape{

float area;

void area(float length,float breadth){

this.area=length*breadth;

}

}

class Rectangle extends Shape{

void parameters(float length,float breadth,float perimeter){

super.area(length,breadth);

System.out.print("Area of this rectangle is "+super.area);

}

}

class ShapeSuper1{

public static void main(String args[]){

Rectangle r1=new Rectangle();

r1.parameters(10.5f,11.5f,44f);

}

}

Try In Editor

Output

Area of this rectangle is 120.75


super keyword for parent class constructor

Example

class Shape{

int length,width;

Shape(int length,int breadth){

this.length=length;

this.width=breadth;

}

}

class Cone extends Shape{

int height;

Cone(int length,int breadth,int height){

super(length,breadth);

System.out.println("Width of this cone is "+super.width);

}

}

class SuperConstructor{

public static void main(String args[]){

Cone r1=new Cone(10,11,8);

}

}

Try In Editor

Output

Width of this cone is 11


You can call super constructor only from the first statement of the child constructor.