In the Java programming language, the keyword "super" is utilized as a reference variable to refer the immediate parent class of an object.
When you create a subclass instance, an implicit instance of the parent class is also created and is referred to by the super reference variable.
With the concept of Inheritance, the keyword "super" entered the picture.
To access the data member or field of the parent class, we can utilize the "super" keyword. This keyword work when both the parent and child classes have fields with the same name.
class Vehicle{ int maxSpeed = 90; } class Bike extends Vehicle{ int maxSpeed = 140; void display(){ System.out.println("Bike Class - Maximum Speed: "+ maxSpeed); System.out.println("Vehicle Class - Maximum Speed: "+ super.maxSpeed); //print Vehicle class maxSpeed variable } } class alpha{ public static void main(String args[]){ Bike bike=new Bike(); bike.display(); } }
Output:
Bike Class - Maximum Speed: 140
Vehicle Class - Maximum Speed: 90
This is used to invoke the parent class method. So, whenever a parent and child class have methods with the same name, we use the super keyword to resolve ambiguity.
class Vehicle{ int maxSpeed = 90; void SpeedDisplay(){ System.out.println("Vehicle Class - Maximum Speed: "+ maxSpeed); } } class Bike extends Vehicle{ int maxSpeed = 140; void SpeedDisplay(){ System.out.println("Bike Class - Maximum Speed: "+ maxSpeed); } void display(){ SpeedDisplay(); super.SpeedDisplay(); // Vehicle class method get print } } class alpha{ public static void main(String args[]){ Bike bike=new Bike(); bike.display(); } }
Output:
Bike Class - Maximum Speed: 140
Vehicle Class - Maximum Speed: 90
The "super" keyword has the ability to access the constructor of the parent class. Another important distinction is that, depending on the situation,'super' can invoke both parametric and non-parametric constructors.
class Vehicle{ int maxSpeed = 90; Vehicle(){ System.out.println("Vehicle Class - Maximum Speed: "+ maxSpeed); } } class Bike extends Vehicle{ int maxSpeed = 140; Bike(){ super(); System.out.println("Bike Class - Maximum Speed: "+ maxSpeed); } } class alpha{ public static void main(String args[]){ Bike bike=new Bike(); } }
Output:
Bike Class - Maximum Speed: 140
Vehicle Class - Maximum Speed: 90
Post your comment