Default method in interface in java

Default methods in interface is a new feature to Java which was introduced as part of Java 1.8.Till Java 1.8 method implementation in an interface was out of scope.In this new approach, it is possible to implement a method in an interface with the default keyword at the beginning of  the method signature.This discussion gives a basic idea about the default method in interface in java

Default method in interface in java

If we have a default method in an interface  and we are extending  the interface,then we can do any of the following depending on our need.

1)Leave the default method

If we are not overriding the default method in the implementing  classes ,then the classes would be using the method defined in the interface.That means our  extended classes inherit the default method.To explain this scenario , let us define an interface with one default method .

IService.java
public interface ISample {
	void doSomething();

	default void printMessage() {
		System.out.println("This is a message from interface");
	}
}

Now lets write a class Service.java which is not implementing the method with default keyword.

public class Sample implements ISample {

	@Override
	public void doSomething() {
		System.out.println("Message from doSomethong() method");

	}

}

Let us create a main class to verify the result.

public class SampleTest {

	public void testDefault() {
		ISample sample = new Sample();
		sample.printMessage();
	}

	public static void main(String[] args) {
		SampleTest sampleTest = new SampleTest();
		sampleTest.testDefault();
	}

}

Now run the program .We can see that the message “This is a message from interface” in  console.

2)Declare the the default method again  in the extended class

That lets the method to be abstract.

3) Define the default method in the extended classes

It lets us to override the method.
In such case , our Sample.java would be :
public class Sample implements ISample {

	@Override
	public void doSomething() {
		System.out.println("Message from doSomethong() method");

	}

	public void printMessage() {
		System.out.println("This is a message from class");
	}

}

If we run the SampleTest.java ,the output would be:This is a message from class.

So overall , default methods allows the programmer to add new functionality to an interface without affecting the implementing classes.Also an implementing class can override the default method ,if needed.

See Related Topics:

Interfaces in Java

Abstract Classes in Java

Collections in Java

Threading in Java