Single Abstract Method Interfaces

Interface in java can have multiple abstract methods, but if an Interface has just one abstract method then is also called a Single Abstract Method Interface or SAM or Functional Interface.

SAM interfaces can be implemented using lambda expressions or method references.

Some examples of SAM in java are java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator and java.util.concurrent.Callable.

package org.wesome.java8;

interface Apple {
    void show();
}

Traditionally up to java 7, the best way to implement interfaces was to create an implementing class and override the method.

package org.wesome.java8;

interface Apple {
    void show();
}

class Fuji implements Apple {
    @Override
    public void show() {
        System.out.println("i love Apple");
    }

    public static void main(String[] args) {
        Apple fuji = new Fuji();
        fuji.show();
    }
}

 

Another way is creating an anonymous inner class as shown below.

package org.wesome.java8;

interface Apple {
    void show();
}

class Fuji {
    public static void main(String[] args) {
        Apple apple = new Apple() {
            @Override
            public void show() {
                System.out.println("i love Apple");
            }
        };
        apple.show();
    }
}

after java 8, it can be done using lambda expression as shown below

package org.wesome.java8;

interface Apple {
    void show();
}

class Fuji {
    public static void main(String[] args) {
        Apple apple = () -> {
            System.out.println("i love Apple");
        };
        /*  since it's a single line method hence input type return and brackets are not required */
        Apple apple1 = () -> System.out.println("i love Apple");

        apple.show();
        apple1.show();
    }
}

 

follow us on