Multiple Inheritance Using Interface in Java
Multiple Inheritance Using Interface in Java
Java
This presentation will delve into the concept of multiple inheritance in Java using interfaces. We will explore the challenges of multiple
inheritance with classes and how interfaces provide a powerful solution.
Multiple Inheritance: Challenges
Diamond Problem Method Ambiguity
Occurs when a subclass inherits from multiple classes that When a subclass inherits multiple methods with the same name
share a common ancestor, leading to ambiguity regarding but different implementations from different parent classes,
which implementation to use for methods inherited from the confusion arises about which method to invoke.
shared ancestor.
Java's Approach to Multiple Inheritance
No Multiple Inheritance
To avoid the complications of the diamond problem and method
ambiguity, Java does not support direct multiple inheritance with
classes.
Interface Solution
Java provides interfaces as a mechanism to achieve multiple inheritance
without the complexities of direct multiple inheritance.
What is an Interface?
1 Reference Type 2
Abstract Methods 3 Static Constants
An interface is a Interfaces define Interfaces can
reference type in methods that are also contain
Java, similar to a declared but not static constants,
class, but with a implemented. which are
different purpose These methods values that are
and structure. are abstract and shared by all
Interfaces cannot must be implementations
have concrete implemented by of the interface.
implementations classes that
for methods. implement the
interface.
Syntax of Interface
interface InterfaceName { // abstract methods }
Implementing Multiple
Interfaces
class ClassName implements Interface1, Interface2 {
// implementation of abstract methods }
Advantages of Interfaces
Code Reusability Interfaces promote code
reusability by allowing multiple
classes to implement the same
interface, sharing the same set of
methods.
interface B {
void display();
}
class C implements A, B {
@Override
public void display() {
System.out.println("This is the display method from class C");
}
}
interface B {
default void display() {
System.out.println("Display method from interface B");
}
}
class C implements A, B {
@Override
public void display() {
A.super.display();
B.super.display();
System.out.println("This is the display method from class C");
}
}