0% completed
The super
keyword in Java is a reference variable used to refer to the immediate parent class object. It serves multiple purposes in inheritance, allowing subclasses to access superclass members (variables and methods) and constructors. Understanding how to effectively use super
is essential for leveraging the full power of inheritance in Java.
In this example, we'll demonstrate how the super
keyword is used to call the superclass constructor and access a superclass method from the subclass.
Explanation:
Superclass (Vehicle
) Components:
brand
, model
brand
and model
of the vehicle.displayInfo()
Subclass (Car
) Components:
extends Vehicle
Car
class inherits from the Vehicle
class, acquiring its variables and methods.super(brand, model);
Vehicle
) constructor to initialize inherited variables.carType
.displayCarType()
super.displayInfo();
Vehicle
) method displayInfo()
to display inherited information.In this example, we'll demonstrate how the super
keyword is used to access superclass variables that may be hidden by subclass variables.
Explanation:
Dog
) Components:
extends Animal
Dog
class inherits from the Animal
class, acquiring its variable and method.super(name);
Animal
) constructor to initialize the inherited name
variable.this.name = "Doggo " + name;
name
variable, differentiating it from the superclass variable.breed
.displayBreed()
this.name
name
variable.super.name
name
variable, allowing access to the hidden variable.The super
keyword in Java plays a crucial role in inheritance by allowing subclasses to interact seamlessly with their superclasses. Whether it's calling the superclass constructor to initialize inherited variables, accessing superclass methods to reuse functionality, or referring to superclass variables that may be hidden by subclass variables, super
provides the necessary tools to maintain a clean and efficient inheritance structure.
.....
.....
.....