Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new method to an interface which is directly implemented by many classes

Tags:

java

interface

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

like image 498
Vikram Darsi Avatar asked Dec 25 '22 15:12

Vikram Darsi


2 Answers

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.

like image 62
user207421 Avatar answered Dec 28 '22 05:12

user207421


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.

like image 27
Tim B Avatar answered Dec 28 '22 05:12

Tim B