Tuesday, April 29, 2014

Java 8 features : default methods

Functional interface can not have more than one abstract method but it can have more than one default methods.


public interface DefaultInterface1 {
   
    public void printMessage1();
   
    default void printMessage2(){
        System.out.println("default method test1");
    }
    default void printMessage3(){
        System.out.println("default method test2");
    }
   
}

you can either use annotations
@FunctionalInterface
public interface DefaultInterface1 {
   
    public void printMessage1();
   
    default void printMessage2(){
        System.out.println("default method test1");
    }
    default void printMessage3(){
        System.out.println("default method test2");
    }
   
}

public class DefaultInterface1Test implements DefaultInterface1 {

    public static void main(String[] args) {
       
        DefaultInterface1Test di1=new DefaultInterface1Test();
       
       
        di1.printMessage1();
//        default method test1
        di1.printMessage2();
//        default method test2
        di1.printMessage3();
    }

    @Override
    public void printMessage1() {
        System.out.println("not default method");
       
    }

}

No comments:

Post a Comment