Monday 16 February 2015

Java8 Method Enhancements

Add a body to a method in a interface?
No, because all methods in an interface are abstract.

Add a static method to an interface?? 
No, because static methods cannot be abstract and be overridden in subclasses. 

...but it was before Java8

In Java8 interfaces can contain abstract method, static methods an default methods. 

  • Static and default methods contain implementation.
  • All abstract, default, and static methods in an interface are implicitly public

Default method:

A default method has the word default and it includes a body with the implementation as we can see the method isAvailable in the following example:


When you extend an interface that contains a default method, you can do the following:

- Override : default boolean isAvailable(LocalDate date){//new implementation}
- Make it abstract: boolean isAvailable(LocalDate date);
- Inherit the default method: not including nothing in the extended interface

In the following example the above interface Agenda is extended in the interface WorkAgenda. The default method is overriden because a new implementation is included.  

In case we would prefer to make it abstract we could write the method signature but without body. A class that implements an interface must implement all the abstract methods declared in the interface.


Static Methods
Including static methods in interfaces replaces the idea of defining utilities in separate Utility class.

The static method is part of the interface and not of the implementing class. So the way to call the method is using the interface name. In the following example the static method formatDate is used in the main method. As formatDate is defined in the interface Agenda, the notation is Agenda.formatDate(Date date);

And remember that when an interface is modified to add a new default or static method, the classes that already implemented the interface do not need to be modified.



No comments:

Post a Comment