Thursday 28 June 2018

Default Methods in Interfaces

This is follow-up from the previous post where we talk about the changes in Interfaces in JDK 8 .

So now we know that Interfaces can also have default methods with the implementation .

Default Methods enable us to add new functionality to existing interfaces and ensure binary compatibility with code written for older versions of those interfaces . In particular , default methods allows us to add methods that accept lambda expressions as parameters to existing interfaces .

We specify the default methods with the "default" keyword at the beginning of the method signature . All the method declarations in an interface are implicitly "public" so we can omit the "public" modifier .

Suppose that we have an interface , MyInterface :

public interface MyInterface
{
  void method1(int i);
  void method2(String s);
  void method3(double d){
  System.out.println("d is "+d);
}
}

And we have a class, MyClass that implements this Interface :

public MyClass implements MyInterface
{
 void method1(int i)
{
  System.out.print("i is"+i);
}

 void method2(String s)
{
  System.out.print("s is"+s);
}

}

This will compile successfully and  method3 will be already defined for MyClass .

We will look into different scenarios that are possible with this implementation . Like what will happen if we implement two interfaces and both of them have a default method with the same signature. Or what will happen if we implement the extended interface and both the parent & child interfaces have same default methods.

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 :) .