Java interface default methods

Java interfaces cannot implement code in the methods declared, instead as you probably know they have to be overridden and implemented in the class that implement that particular interface. However, one feature in Java since version 8 is that you can define methods as default in an interface and provide the implementation for it as well, which means that the class or classes that implement that particular interface don’t have to override those methods, but they can still be reached from the caller of that class.

This example shows how to implement such a default method. In the code we have a class User, which implements an interface Role with a default method getRole. The default method is not overridden in the class since it’s not necessary:

When the getUser method is called, the default method in the Role interface is invoked, returning the value “Contributor”.

Now if we would override that default method and return another String in the User class, the default implementation would not be invoked. Let’s say we override the getRole method and implement logic that says that if you have been a registered user for over 3 months, you automatically becomes an administrator, otherwise your role is still contributor:

In the code above the default implementation of the method getRole is only invoked if the user have been registered 3 months or less. Otherwise it is not invoked, and instead the string is returned from the User class.

The output from the code above is “Admin” since the registered date was 4 months ago.

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?