I have a small question on java interfaces
Is there any way to add a new method to java interface without modifying the classes that are implementing it.
condition is that I should not introduce new interface
Is there any way to add a new method to java interface without modifying the classes that are implementing it.
No.
condition is that I should not introduce new interface
If the condition also includes not modifying the many classes that directly implement the interface, you have been given an impossible task.
This is the reason why interfaces are often accompanied by abstract Adapter
classes, that implement all the methods in a do-nothing way. Implementation classes then extend the adapter rather than implementing the interface, so that if you need to add an interface you only need to modify the interface and the adapter.
What you are trying to do is fundamentally impossible. Unless (as was just pointed out in the comments) you use Java 8.
Java 8 has introduced a concept of default or defender methods that allow you to add a method to an interface and provide a default implementation of that method within the interface.
http://zeroturnaround.com/rebellabs/java-8-explained-default-methods/
The rest of the answer applies to any version of Java before 8:
An interface describes the methods in a class. If you add a new method to an interface then all classes that implement the interface must implement the method. Unless by some stroke of luck the method you are adding already exists in every single implementing class this is just impossible without either adding a new interface or changing the classes.
If your interface were an Abstract Class then you could add a stub method that does nothing and allow that to be overridden but interfaces have no concept of optional methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With