Reputation:
If we have an interface which has different implementations in many classes and we must add another one new method in this interface, who would be the shorter way to solve the issue of overriding that method in all implementing classes?
Upvotes: 3
Views: 3318
Reputation: 95508
You can take a look at default methods. The idea is that you provide a default implementation in the interface. Keep in mind that this only applies to Java 8+. If you are doing this in older versions of Java, you will have no choice but to implement the method in all classes that implement the interface.
Using default methods, Oracle were able to solve the backwards-compatibility issues involved with adding the new streaming/lambda methods to the collections API.
Upvotes: 6
Reputation: 49606
When you add new method in interface, you need realize this method in all classes, which implements your interface.
In Java 8, you can сreate default
method with realization. For example:
interface YourInterface {
default void method() {
// do something
}
}
class YourClass implements YourInterface {
public static void main(String[] args) {
YourClass yourClass = new YourClass();
yourClass.method();
}
}
You may read about default methods in Oracle Tutorials.
Upvotes: 1