Archives for 

Core Java

Core Java Tutorial

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 .

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

Let us create a main class to verify the result.

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 would be :

If we run the ,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