Adding a Method to an Existing Interface

If we have an interface that has different implementations in many classes, and we have to add another new method in that interface, who would be a shorter way to solve the problem of overriding this method in all implementation classes?

+3


source to share


2 answers


You can look at the default methods . The idea is that you provide a default implementation in the interface. Be aware that this only applies to Java 8+. If you do this in older versions of Java, you will have no choice but to implement this method in all classes that implement the interface.



By using the default methods, Oracle was able to address backward compatibility issues associated with adding new streaming / lambda methods to the collection API.

+6


source


When you add a new method to an interface, you need to implement that method in all classes that implement your interface.

In Java 8, you can create a method default

with an implementation. 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 can read about default methods in the Oracle Tutorials .

+1


source







All Articles