Super keyword in Java
super keyword in Java
1.super is a keyword that refers to the object of current base class .
2.It can be used to replace derived class variable with base class level variable.
3.It is also used to call parent/base class method/function.
4.It is also used to call parent/base class overloaded constructor.
1. super keyword with variable
By using super keywrod we can replace derived class variable with base class varible. For better understanding see the below example.
//Base class
class Parameter
{
int height=10,width=20;
}
//derived class
class Rectangle extends Parameter
{
int height=5,width=6;
public void area()
{
int ar;
ar=height*width;
System.out.println("Area without super="+ar);
//here derived class variable is replaced with base class variable
ar=super.height*super.width;
System.out.println("Area with super="+ar);
}
}
class Easy
{
public static void main(String[] args)
{
//Creating instance(object) of class
Rectangle obj=new Rectangle();
obj.area();
}
}
/*
### Output ###
Area without super=30
Area with super=200
*/
2. super keyword with function
By using super keywrod we can also call base class function from derived class. For better understanding see the below example.
//Base class
class Square
{
void area(int side)
{
int ar=side*side;
System.out.println("Area of square="+ar);
}
}
//derived class
class Rectangle extends Square
{
int height=5,width=6;
public void area()
{
int ar;
ar=height*width;
System.out.println("Area of Rectangle="+ar);
//calling base class function using super keyword
super.area(10);
}
}
class Easy
{
public static void main(String[] args)
{
//Creating instance(object) of class
Rectangle obj=new Rectangle();
obj.area();
}
}
/*
### Output ###
Area of Rectangle=30
Area of square=100
*/
3. super keyword with constructor
By using super keywrod we can also call constructor of base class function from derived class. For better understanding see the below example.
//Base class
class Square
{
//paramaterised constructor of base class
Square(int side)
{
int ar=side*side;
System.out.println("Area of square="+ar);
}
}
//derived class
class Rectangle extends Square
{
int height=5,width=6;
//default constructor of derived class
Rectangle()
{
//calling base class constructor
super(12);
int ar;
ar=height*width;
System.out.println("Area of Rectangle="+ar);
}
}
class Easy
{
public static void main(String[] args)
{
//Creating instance(object) of class
Rectangle obj=new Rectangle();
}
}
/*
### Output ###
Area of square=144
Area of Rectangle=30
*/