Java Program to demonstrate multiple inheritance using interfaces.
Objective
Write a Java program to demonstrate Multiple Inheritance using interfaces.
Algorithm / Approach
- Create a first interface
SubMarkswith a methodgetMarks(). - Create a second interface
Sportswith a methodsportMarks(). - Create a
Resultclass that implements BOTH interfaces separated by a comma (implements SubMarks, Sports). - Provide concrete implementations for both methods inside the
Resultclass. - Call both methods from the main class.
Result.java
import java.util.Scanner;
interface SubMarks {
public void getMarks();
}
interface Sports {
public void sportMarks();
}
class Result implements SubMarks,Sports {
int marks,sport,total;
Scanner s = new Scanner(System.in);
public void getMarks() {
System.out.print("Subject Marks: ");
marks = s.nextInt();
}
public void sportMarks() {
System.out.print("Sport Marks: ");
sport = s.nextInt();
}
public void display() {
total = marks+sport;
System.out.println("Total - "+total);
}
}
class Main {
public static void main(String[] a)
{
Result r =new Result();
r.getMarks();
r.sportMarks();
r.display();
}
}
Expected Output
Subject Marks: 90 Sport Marks: 80 Total - 170
Explanation of the Program
- Java strictly prohibits a class from extending more than one parent class (Multiple Inheritance of State) because it leads to the "Diamond Problem" (ambiguity if both parents have a method with the same name).
- However, Java ALLOWS multiple inheritance of interfaces. Why? Because interfaces only contain empty method signatures.
- If both interfaces require a method called
getMarks(), there is no ambiguity. The child class just provides one implementation that satisfies both contracts.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)