Multilevel inheritance is a type of inheritance in Java where a derived class inherits properties from a base class, which in turn is derived from another base class. In other words, a subclass can inherit from a superclass, and the superclass can itself be a subclass of another superclass, and so on. This creates a chain of inheritance where each class in the chain inherits properties from its direct superclass and its indirect superclass.
class A {
// code to be executed
};
class B extends A {
// code to be executed
};
class C extends B {
// code to be executed
};
This code defines four classes: Animal
, Dog
, Cat
, and MultilevelInheritance
.
Animal
, Dog
, and Cat
are classes that are related by inheritance, with Dog
being a subclass of Animal
, and Cat
being a subclass of Dog
.
The Animal
class has a constructor that prints the message “This is an Animal”. The Dog
class has a constructor that prints the message “This is a Dog”. The Cat
class has a constructor that prints the message “This is a Cat”. Since Cat
is a subclass of Dog
, which is a subclass of Animal
, it inherits the constructors of both Dog
and Animal
.
The MultilevelInheritance
class has a main
method that creates a new Cat
object called obj
.
class Animal {
Animal() {
System.out.println("This is an Animal");
}
};
class Dog extends Animal {
Dog() {
System.out.println("This is a Dog");
}
};
class Cat extends Dog {
Cat() {
System.out.println("This is a Cat");
}
};
class MultilevelInheritance {
public static void main(String[] args) {
Cat obj = new Cat();
}
}
This is an Animal
This is a Dog
This is a Cat
This code defines four classes: Animal
, Dog
, Cat
, and MultilevelInheritance
.
Animal
, Dog
, and Cat
are classes that are related by inheritance, with Dog
being a subclass of Animal
, and Cat
being a subclass of Dog
.
The Animal
class has a method printAnimal()
that prints the message “This is an Animal”. The Dog
class has a method printDog()
that prints the message “This is a Dog”. The Cat
class has a method printCat()
that prints the message “This is a Cat”. Since Cat
is a subclass of Dog
, which is a subclass of Animal
, it inherits the methods of both Dog
and Animal
.
The MultilevelInheritance
class has a main
method that creates a new Cat
object called obj
and calls its printAnimal()
, printDog()
, and printCat()
methods.
class Animal {
public void printAnimal() {
System.out.println("This is an Animal");
}
};
class Dog extends Animal {
public void printDog() {
System.out.println("This is a Dog");
}
};
class Cat extends Dog {
public void printCat() {
System.out.println("This is a Cat");
}
};
class MultilevelInheritance {
public static void main(String[] args) {
Cat obj = new Cat();
obj.printAnimal();
obj.printDog();
obj.printCat();
}
}
This is an Animal
This is a Dog
This is a Cat