Java 8 Interface – Default and static methods

Since Java 8 it’s possible to add default and static methods in interfaces. Due to the new methods, it’s not necessary to implement the method in every class. The interface provides the implementation already. In previous versions, an interface could have abstracts methods only.

Default Method

The default method has the default signature. It provides the implementation for the method and can be overridden in the implemented class.

public interface IPerson {

     default String name() {
        return "Joe";
    }
}

It makes it easier to add new methods, without breaking the rules for the class. If the method does not exist the class it will take the default implementation. Otherwise, the class implementation will be used, if the name exist already. Of course, the default implementation can be overridden to change the implementation and it is also possible to use the super call execute the default implementation. In our example above the call in the class look like:

public class PersonImpl implements IPerson {

     @Override
     public String name() {
        return IPerson.super.name();
    }
}

If you extend an interface with a default method, which name already exists in the parent interface, the child interface implementation will be executed.

Now an interesting point. If you want to implement a class with two interfaces and both of them, have a default method with exactly the same name, the compiler throws the following error:

Error:(1, 8) java: class PersonImpl inherits unrelated defaults for name() from types IPerson and ISecondInterface

Then it becomes necessary to implement the method in the class. The program can’t decide which method should be prioritized.

Static Method

The static method has the static signature. It behaves the same way as a constant variable and can’t be overridden.

public interface IPerson {

    static int getAge() {
        return 42;
    }
}

The call to the static method is exactly the same as to any other static method: IPerson.getAge();

chevron_left
chevron_right

Leave a comment

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

Comment
Name
Email
Website

This site uses Akismet to reduce spam. Learn how your comment data is processed.