Wednesday, November 19, 2014

Java 8 : Interfaces and Default Methods

Hi ,

Today I am going to post a bit about some of the exciting features of Java 8.

Pre-requisites  :

1> Install java 8 SDK
2> Install Eclipse Luna (Eclipse 4.4.1)

Without Eclipse Luna 4.4.1 , it will be very difficult to run programs in Java 8. So please download and install the Eclipse Luna Build .

So, let's get started with the good stuff .

Default Methods :

Now in java 8 , we can have methods with default signature in interface, which will have body logic or implementation logic . 

So, let's say I have an interface called Person below :

public interface Person {

default void sayHello() {
              System.out.println("Hello there in Person!");
    }

}

As you can see if encapsulate a method name in the interface with default signature, you can add your logic in it.

Now what happens , when I have another interface with same method name but different implementation logic and I try to implement both of them in a single class ?

public interface Male {

default void sayHello() {
              System.out.println("Hi there in Male ");
    }

}

My implementation class(Sample.java) is shown below :


As you can see, here the compile time error is thrown because the compiler is not understanding which "sayHello()" method it should implement.

So to resolve this ambiguity, we can override the sayHello() method in  the implementation class itself  like this :

public class Sample implements Person, Male {

//override the sayHello to resolve ambiguity
public void sayHello() {
   
    }

}

OR

We can just call the appropriate / desired interface method directly inside .
To do this, we have to use the syntax : "Interface.super.methodname()"

public class Sample implements Person, Male {

//override the sayHello to resolve ambiguity
public void sayHello() {

Person.super.sayHello();
Male.super.sayHello();
   
    }

}

So a default method looks a lot like an abstract class implementation , does n't it ?
However, there is a subtle difference : An abstract class holds the state of its object as it can have constructors .But interfaces in java 8 with default methods cannot have constructors and as such cannot hold the state of an object. Default method should be used for backward compatibility. Whenever you want to add additional functionality in an existing legacy interface you can use default methods without breaking any existing implement or classes.


That's all on interfaces from java 8 perspective .  I will come up with a new feature of Java 8 on my next post which will be related to Lambda Expressions .

No comments:

Post a Comment