Can interfaces be used to achieve multiple inheritance in Java?

Java MCQ: Can interfaces be used to achieve multiple inheritance in Java?

A. Yes
B. No

Answer:

A. Yes

Explanation:

Yes, interfaces in Java can be used to achieve multiple inheritance. While Java does not support multiple inheritance with classes (i.e., a class cannot extend more than one class), it allows a class to implement multiple interfaces. This means that a class can inherit method signatures from several interfaces, effectively allowing for a form of multiple inheritance.

Interfaces are abstract types that declare methods but do not provide implementations. A class that implements an interface must provide implementations for all the methods declared in the interface. If a class implements multiple interfaces, it must implement the methods of all those interfaces, thereby inheriting from multiple sources:


interface Flyable {
    void fly();
}

interface Swimmable {
    void swim();
}

class Duck implements Flyable, Swimmable {
    public void fly() {
        System.out.println("The duck flies.");
    }

    public void swim() {
        System.out.println("The duck swims.");
    }
}

In this example, the Duck class implements both the Flyable and Swimmable interfaces. It inherits the method signatures from both interfaces and provides specific implementations for fly() and swim(). This approach allows Duck to “inherit” behaviors from multiple sources, demonstrating the concept of multiple inheritance through interfaces.

Using interfaces to achieve multiple inheritance helps to avoid the complexities and ambiguities associated with multiple inheritance in classes, such as the diamond problem. It allows for greater flexibility and modularity in code design, making it easier to manage and extend functionality in Java applications.

Reference links:

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

Leave a Comment

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

Scroll to Top