What is a multilevel inheritance in Java?

Java MCQ: What is a multilevel inheritance in Java?

A. A class extends two or more classes
B. Two or more classes extend the same class
C. A class extends another class which also extends another class
D. All of the above

Answer:

C. A class extends another class which also extends another class

Explanation:

Multilevel inheritance in Java refers to a scenario where a class is derived from another class, which in turn is derived from another class, creating a chain of inheritance. This form of inheritance allows a subclass to inherit the properties and behaviors of its immediate superclass as well as those of its ancestor classes. Multilevel inheritance enables more complex class hierarchies and promotes code reuse across multiple levels.

For example, consider the following class hierarchy:


class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Mammal extends Animal {
    void walk() {
        System.out.println("This mammal walks.");
    }
}

class Dog extends Mammal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

In this example, Dog is a subclass of Mammal, which is a subclass of Animal. Through multilevel inheritance, the Dog class inherits methods from both Mammal and Animal, allowing a Dog object to perform actions such as eat(), walk(), and bark().

Multilevel inheritance can be useful in modeling real-world relationships where objects share common characteristics but also have unique features that distinguish them from others in the hierarchy. However, it is important to manage such hierarchies carefully to avoid complexity and ensure that the relationships between classes remain clear and maintainable.

Reference links:

https://www.javaguides.net/p/java-inheritance-tutorial.html

Leave a Comment

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

Scroll to Top