0% completed
Multilevel Inheritance is a type of inheritance in Java where a class is derived from a subclass, creating a chain of inheritance. In other words, a subclass becomes the superclass for another subclass. This forms a multilevel hierarchy, allowing the properties and behaviors of multiple classes to be inherited through different levels.
The syntax for implementing multilevel inheritance involves chaining the extends
keyword. Here's the general structure:
class GrandparentClass { // Grandparent class members } class ParentClass extends GrandparentClass { // Parent class members } class ChildClass extends ParentClass { // Child class members }
GrandparentClass
: The top-level superclass.ParentClass
: Inherits from GrandparentClass
and acts as a superclass for ChildClass
.ChildClass
: Inherits from ParentClass
.In this example, we'll demonstrate multilevel inheritance by creating a Vehicle
class, a Car
class that inherits from Vehicle
, and a SportsCar
class that inherits from Car
. All classes will be defined within a single Solution.java
file for simplicity.
Explanation:
Vehicle
Class (Grandparent Class):
brand
, model
represents general characteristics common to all vehicles.brand
and model
of the vehicle.displayVehicleInfo()
Displays the vehicle's brand and model.Car
Class (Parent Class):
extends Vehicle
Car
class inherits from the Vehicle
class, acquiring its attributes and methods.year
super(brand, model);
Vehicle
) constructor to initialize inherited variables.year
.displayCarInfo()
SportsCar
Class (Child Class):
extends Car
SportsCar
class inherits from the Car
class, gaining access to its attributes and methods.color
super(brand, model, year);
Car
) constructor to initialize inherited variables.color
.displaySportsCarInfo()
Multilevel Inheritance in Java allows the creation of a hierarchical class structure where a subclass inherits from another subclass, forming a chain of inheritance. By leveraging the extends
keyword, each subclass can inherit and build upon the properties and methods of its immediate superclass. This promotes code reusability, logical organization, and scalability within Java applications.
.....
.....
.....