Tuesday 26 September 2017

Default and Static Methods in Interface

Default and Static Methods in Interface!

Before Java 8, interfaces could have only public abstract methods. It was not possible to add new functionality to the existing interface without forcing all implementing classes to create an implementation of the new methods, nor it was possible to create interface methods with an implementation.

Starting with Java 8, interfaces can have static and default methods that, despite being declared in an interface, have a defined behavior.

Static Method

Consider the following method of the interface (let’s call this interface Person):

static String nationality() {
    return "Indian";
}

The static nationality() method is available only through and inside of an interface. It can’t be overridden by an implementing class.

To call it outside the interface the standard approach for static method call should be used:

String nationality = Person.nationality();

Default Method
Default methods are declared using the new default keyword. These are accessible through the instance of the implementing class and can be overridden.

Let’s add a default method to our Person interface, which will also make a call to the static method of this interface:

default String getRating() {
    return "Good ";
}

Assume that this interface is implemented by the class Employee. For executing the default method an instance of this class should be created:

Person employee = new Employee();
String overview = employee .getRating();

No comments:

Post a Comment