Thursday, 14 January 2016

Java Tutorial : Java Interface (Evolving Interfaces using extends)

Master Core Java Concepts!

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

Subscribe Now on YouTube

What Are Evolving Interfaces in Java?

In Java, once you publish an interface and classes start implementing it, changing that interface directly can cause problems. If you add a new abstract method to an existing interface—like adding sayBye() to a DoIt interface—every class that implements DoIt will break until it provides an implementation for that new method.

To evolve an interface without breaking existing classes, you can create a new interface that extends the original interface.

How to Evolve an Interface Using extends

Instead of modifying the original interface, follow this clean approach:

  • Keep the Original Interface Intact: Leave DoIt with its original sayHi() method so existing classes continue working without changes.
  • Create an Extended Interface: Define a new interface, such as DoItPlus, that uses extends DoIt and declares the new sayBye() method.
  • Upgrade When Ready: Existing classes can stay on DoIt, or they can implement DoItPlus later to support both sayHi() and sayBye().

Code Example: Evolving Interfaces in Java

public interface DoIt {
  void sayHi();
}

public interface DoItPlus extends DoIt {
  void sayBye();
}

public class MyClass implements DoItPlus {
  public void sayHi() { System.out.println("Hi"); }
  public void sayBye() { System.out.println("Bye"); }
}

Key Takeaways

  1. Backward Compatibility: Extending an interface protects existing implementations from compilation errors.
  2. Flexible Upgrades: Classes can adopt the new DoItPlus interface only when they are ready to implement the added methods.
  3. Clean Polymorphism: You can still reference a MyClass object using either a DoIt or DoItPlus reference.

Watch More Java Tutorials:

No comments:

Post a Comment

Tutorials