user5033850
user5033850

Reputation:

Adding a method in an existing interface

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

Answers (2)

Vivin Paliath
Vivin Paliath

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

Andrew
Andrew

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

Related Questions