Sunday 24 June 2018

Interfaces in Java 8

Interfaces have evolved a lot in Java 8 . They provide much more flexibility now .

Suppose we have an interface defined as follows :
public interface MyInterface
{
void myMethod1(int i);
void myMethod2(String s);
}

Later on we decide to add one more method : myMethod3(double d) to the interface . So , all the classes implementing the interface would have to implement the new method as well . That will break the existing functionality .

We have different approaches to solve this :
1) Extend the interface to create a new interface with the new functionality :
public interface MyNewInterface extends MyInterface
{
void myMethod3(double d);
}

2) Another approach would be defining new methods as default methods .

public interface MyInterface
{
void myMethod1(int i);
void myMethod2(String s);
void myMethod3(double d)
{
// implementation
System.out.print("Value is" +d );
}

Note that we have to define implementation for default methods .


We will look into default methods in my next post :) .


1 comment: