What is Super keyword

It is a reference variable which always refers to the immediate parent class object. It performs following operations:

1. Used to call the immediate parent class constructor.

e.g.

class Fruit{
Fruit(){
System.out.println(“Fruit class created”);
}
}
class Apple extends Fruit{
Apple () {
super();//It will call parent class constructor
System.out.println(“Apple class created”);
}
public static void main(String args[]){
Apple a=new Apple ();
}
}

Output
Fruit class created
Apple class created

Learn Java

2. Refer immediate parent class instance variable

e.g. 

class Fruit{
int quantity=20;
}
public class Apple extends Fruit{
int quantity=10;
void show(){
System.out.println(super.quantity);/*It will print Fruit’s quantity that is Refer immediate parent class instance variable */
System.out.println(quantity);
}
public static void main(String args[]){
Apple ap=new Apple ();
ap.show();
}
}

Output
20
10

3. Can call immediate parent class method

e.g.

class Fruit{
void print(){
System.out.println("Fruit class created");}
}
public class Apple extends Fruit{
void print(){
System.out.println("Apple class created");
}
void show(){
super.print();// It will call parent class method
print(); // It will call apple class method
}
public static void main(String args[]){
Apple ap = new Apple();
ap.show();
}
}

Output
Fruit class created
Apple class created
Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!

Course Schedule

Name Date
Python Course 2021-07-31 2021-07-25
(Sat-Sun) Weekend batch
View Details
Python Course 2021-08-07 2021-08-01
(Sat-Sun) Weekend batch
View Details
Python Course 2021-08-14 2021-08-08
(Sat-Sun) Weekend batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *