How to Implement Multiple Inheritance by Using Interfaces in Java?
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when methods with the same signature exist in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class method gets the priority.
Interface is just like a class, which contains only abstract methods. In this article, we will discuss How to Implement Multiple Inheritance by Using Interfaces in Java.
Syntax:
Class super
{
---
----
}
class sub1 Extends super
{
----
----
}
class sub2 Extend sub1
{
-----
-----
}
Implementation
Multiple inheritances can be achieved through the use of interfaces. Interfaces are similar to classes in that they define a set of methods that can be implemented by classes. Here’s how to implement multiple inheritance using interfaces in Java.
Step 1: Define the interfaces
interface Interface1 {
void method1();
}
interface Interface2 {
void method2();
}
Step 2: Implement the interfaces in the class
public class MyClass implements Interface1, Interface2 {
public void method1() {
// implementation of method1
}
public void method2() {
// implementation of method2
}
}
Step 3: Create an object of the class and call the interface methods
MyClass obj = new MyClass();
obj.method1();
obj.method2();
Example:
Java
interface Walkable {
void walk();
}
interface Swimmable {
void swim();
}
class Duck implements Walkable, Swimmable {
public void walk()
{
System.out.println( "Duck is walking." );
}
public void swim()
{
System.out.println( "Duck is swimming." );
}
}
class Main {
public static void main(String[] args)
{
Duck duck = new Duck();
duck.walk();
duck.swim();
}
}
|
Output:
Duck is walking.
Duck is swimming.
Last Updated :
08 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...