The super keyword in Java is a reference variable that is used to refer immediate parent class object.
Use of Super Keyword :
- it is used to refer instance variable of an immediate Parent class
- it is used to refer Method of an immediate Parent Class
- it is used to refer Constructor of an immediate Parent Class
super keyword in java |
☆Refer instance variable of an immediate Parent Class :
When you have a variable in a child class that is also present in the parent class, you must use the super keyword to access the parent class variable.
Example :
- without super keyword Example
//Parent class
class A
{
int a = 25;
}
//Child class
class B extends A
{
/* The same variable a is declared in the Subclass
* which is already present in the Superclass
*/
int a = 50;
void print()
{
System.out.println(a);
}
public static void main(String args[])
{
B obj = new B();
obj.print();
}
}
Output :
50
- using Super Keyword Example
//Parent class
class A
{
int a = 25;
}
//Child class
class B extends A
{
/* The same variable a is declared in the Subclass
* which is already present in the Superclass
*/
int a = 50;
void print()
{
System.out.println(super.a);
}
public static void main(String args[])
{
B obj = new B();
obj.print();
}
}
Output :
25
☆Refer Method of an immediate Parent Class :
The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.
Example :
class Vehicle
{
void color()
{
System.out.println("red...");
}
}
class Car extends Vehicle
{
void color()
{
System.out.println("black...");
}
void price()
{
System.out.println("20Lakh");
}
void print()
{
super.color();
price();
}
}
class TestSuper2
{
public static void main(String args[])
{
Car ob = new Car();
ob.print();
}
}
Output :
red...
20Lakh
☆Refer Constructor of an immediate Parent Class :
- super keyword is used to refer Constructor of an immediate Parent Class
Example :
class A
{
A()
{
System.out.println("class A constructor");
}
}
class B extends A
{
B()
{
super();
System.out.println("class B constructor");
}
}
class Test
{
public static void main(String args[])
{
B ob = new B();
}
}
Output :
class A constructor
class B constructor
Also read- this keyword in java
Tags:
Java