Wednesday, 13 January 2016

Java Tutorial : Interface extends Interface

Master Core Java Step-by-Step!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential interview insights!

Subscribe Now on YouTube

Interface Inheritance: How One Interface Extends Another

In Java, inheritance isn't limited strictly to classes. An interface can also inherit properties and methods from other interfaces using the extends keyword.

While a class implements an interface using implements, an interface inherits from another interface using extends. This distinction allows you to build modular, layered contracts that can grow and specialize over time.

Why Do Interfaces Extend Other Interfaces?

Interface inheritance provides significant design advantages in Object-Oriented Programming:

  • Interface Segregation: Start with simple, focused contracts and extend them to add advanced capabilities without bloating base definitions.
  • Multiple Inheritance of Type: Unlike classes, a single interface can extend multiple super-interfaces simultaneously by separating them with commas.
  • Polymorphic Reusability: Any class that implements a sub-interface automatically becomes compatible with all parent interfaces in the chain.

Code Example: An Interface Extending Another Interface

// Base interface
interface Printable {
  void print();
}

// Sub-interface extending Printable
interface Showable extends Printable {
  void show();
}

// Class implementing the sub-interface must implement all inherited methods
class Document implements Showable {
  @Override
  public void print() {
    System.out.println("Printing document...");
  }

  @Override
  public void show() {
    System.out.println("Showing document on screen...");
  }
}

public class Test {
  public static void main(String[] args) {
    Document doc = new Document();
    doc.print();
    doc.show();
  }
}

Output:

Printing document...
Showing document on screen...

Key Rules for Interface-to-Interface Inheritance

  1. Use 'extends', Not 'implements': An interface always uses the extends keyword to inherit from one or more interfaces.
  2. Full Obligation for Concrete Classes: Any concrete class that implements a sub-interface must provide method bodies for all abstract methods in both the parent and child interfaces.
  3. Multiple Extension Allowed: An interface can inherit from several parent interfaces at once: interface C extends A, B { }.

Watch More Java Interface Tutorials:

No comments:

Post a Comment

Tutorials