Master Core Java Concepts!
Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!
Subscribe Now on YouTubeWhat 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
DoItwith its originalsayHi()method so existing classes continue working without changes. - Create an Extended Interface: Define a new interface, such as
DoItPlus, that usesextends DoItand declares the newsayBye()method. - Upgrade When Ready: Existing classes can stay on
DoIt, or they can implementDoItPluslater to support bothsayHi()andsayBye().
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"); }
}
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
- Backward Compatibility: Extending an interface protects existing implementations from compilation errors.
- Flexible Upgrades: Classes can adopt the new
DoItPlusinterface only when they are ready to implement the added methods. - Clean Polymorphism: You can still reference a
MyClassobject using either aDoItorDoItPlusreference.
No comments:
Post a Comment