+1 vote
in JAVA by
What is a default method and when do we use it?

1 Answer

0 votes
by
A default method is a method with an implementation – which can be found in an interface.

We can use a default method to add new functionality to an interface while maintaining backward compatibility with classes that are already implementing the interface:

public interface Vehicle {

    String getBrand();

    String speedUp();

    String slowDown();

    default String turnAlarmOn() {

        return "Turning the vehice alarm on.";

    }

    default String turnAlarmOff() {

        return "Turning the vehicle alarm off.";

    }

}

Usually, when a new abstract method is added to an interface, all implementing classes will break until they implement the new abstract method. In Java 8, this problem has been solved by the use of the default method.

For example, the Collection interface does not have a forEach method declaration. Thus, adding such a method would simply break the whole collections API.

Java 8 introduces the default method so that the Collection interface can have a default implementation of the forEach method without requiring the classes implementing this interface to implement the same.
...