Java | ‘default’ method implementation for methods in Java interfaces

|
| By Webner

Default method, a new concept used for interfaces has been added to Java 8.

Purpose: In Java 7 or older, classes implementing an interface were forced to implement each method of the interface. Consider a long running project in which an interface is implemented by several classes and then you add couple of new methods to the interface. That would mean implementing these methods in every class implementing the interface. This can be very time consuming process.

In Java 8, we can make the new methods as default and let the developer decide whether he/she needs to implement this method or not.

Significance:This is helpful if we want to upgrade any existing application. We do not need to change at multiple places rather implement the new method only in the class where needed.

Syntax:

public interface MyInterfcae {
default void show() {
System.out.println("Hello !");
}
}

Example 1:

interface MyInterfcae {
public void oldMethod();
default void newMethod() {
// some new functionality added
}}
class ClassA implements MyInterfcae {
@Override
public void oldMethod() {
}
}

Explanation:In the above example, there is no compile time error while implementing MyInterface –
“must inherit the unimplemented methods”. This is because we have used a new keyword “default” with newMethod that came into existence with Java 8. So, we are not forced to override the default method – newMethod() in ClassA.

Default method body can be overridden if needed:

Example 2:

interface MyInterface {
public void oldMethod();
default void newMethod() {
System.out.println("MyInterface");
}}
class ClassA implements MyInterface {
@Override
public void oldMethod() {
System.out.println("Old method");}
@Override
public void newMethod() {
System.out.println("Default Method");
}}

Another example: ‘List’ or ‘Collection’ interfaces did not have ‘forEach’ method declaration. Thus, adding such method would break the collection framework implementations.
Java 8 introduced default method so that List/Collection interface could have a default type of ‘forEach method’, and all the classes that were implementing these interfaces need not to implement it.
Below is an example showing how to use new forEach method added in Iterable interface.

Example 3:

List < String > list = new ArrayList < > ();
list.add("John");
list.add("Kate");
list.add("Rein");
list.forEach(name - > System.out.println(name));

Output:

John
Kate
Rein

Leave a Reply

Your email address will not be published. Required fields are marked *