Java Program to demonstrate inheritance of interfaces.
Objective
Write a Java program to demonstrate how an interface can inherit from another interface.
Algorithm / Approach
- Create a base interface
SubMarkswithgetMarks(). - Create a child interface
Sportsthatextends SubMarks, addingsportMarks(). - Create a
Resultclass that implements ONLY theSportsinterface. - Because
Sportsinherited fromSubMarks, theResultclass is legally forced to implement BOTH methods. - Execute the code from main.
Result.java
import java.util.Scanner;
interface SubMarks {
public void getMarks();
}
interface Sports extends SubMarks {
public void sportMarks();
}
class Result implements 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
- Just as classes can inherit from other classes, interfaces can inherit from other interfaces.
- Crucially, an interface uses the
extendskeyword to inherit from another interface, NOT theimplementskeyword. - The
Resultclass only declaresimplements Sports, but because it's a chain, it absorbs all method contracts up the hierarchy.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)