3

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?

1
  • 1
    Before Java8 it is not possible to have a default method without using abstract class as opposed to an interface. Commented Jun 30, 2015 at 16:27

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.