Friday, 22 April 2016

How can define Default method in interfaces (Java 8) ?


Default method in interface

Java 8 allows to define default method in interface, to add default implementation by using "default " keyword

package com.genius;
interface MyInterface{ 
  abstract void add();

  default void display(){
    System.out.println("default method of interface");
  }
}


BONUS QUESTIONS
Q1. Can we have a default method with body in the interface without specifying the keyword "default" ?
No, Compilation error will occur.
It will treat it as an abstract method so it shouldn't have the body.


Q2. Can a class implement two Interfaces having default method with same signature ?
public interface Interface1 {
  default public void show() { … }
}

public interface Interface2
  default public void show() { … }

public class MyClass implements Interface1, Interface2

No, Compilation error "Duplicate Default Methods"


Q3. What will happen using above example, if we make method as abstract in second interface ?
public interface Interface1 {
  default public void show() { … }
}

public interface Interface2
  public void show() { … }

public class MyClass implements Interface1, Interface2

Same problem, Compilation error "Duplicate Default Methods"


Q4. What will happen using above example, if we override the conflicting method in the Class ?
public interface Interface1 {
  default public void show() { … }
}

public interface Interface2
  default public void show() { … }

public class MyClass implements Interface1, Interface2 {
  public void show() { … }
}

No compilation error, and class method will be executed.


Q5. What will happen using above example, if there is a default method conflict as mentioned above and we have same signature method in the base class instead of overriding in the existing class ?
public interface Interface1 {
  default public void show() { … }
}

public interface Interface2
  default public void show() { … }

public class BaseClass {
  public void show() { … }
}

public class MyClass extends BaseClass implements Interface1, Interface2

No compilation error, as base class method have precedence over the Interface Default methods.


Q6. If there is a conflict between Base Class Method definition and Interface Default method definition, which definition is used ?
Method from Base class


Q7. If there is a conflict between Base Class Method definition, Interface Default method definition and Derived class Method definition, which definition is used ?
Method from Derived class

No comments:

Post a Comment

Note: only a member of this blog may post a comment.