Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate inheritance of interfaces.

Java Code Example — Abstract and Interface Programs

ADVERTISEMENT

Java Program to demonstrate inheritance of interfaces.

Objective

Write a Java program to demonstrate how an interface can inherit from another interface.

Algorithm / Approach

  1. Create a base interface SubMarks with getMarks().
  2. Create a child interface Sports that extends SubMarks, adding sportMarks().
  3. Create a Result class that implements ONLY the Sports interface.
  4. Because Sports inherited from SubMarks, the Result class is legally forced to implement BOTH methods.
  5. 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 extends keyword to inherit from another interface, NOT the implements keyword.
  • The Result class only declares implements Sports, but because it's a chain, it absorbs all method contracts up the hierarchy.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT