Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Java 8 Interview Questions and Answers

Question: Can you create your own functional interface?
Answer:
Yes, you can create your own functional interface. Java can implicitly identify functional interface but you can also annotate it with @FunctionalInterface.
Example:
Create interface named "Readable" as below:
public interface Readable {
    void read();
    default void readBook()
    {
        System.out.println("Reading the book.");
    }
}

Create main class named "MyFunctionalInteface":
public class MyFunctionalInteface {
    public static void main(String[] args)
    {
        MyFunctionalInteface myFuncInterface = new MyFunctionalInteface();
        myFuncInterface.readMyBook(() -> System.out.println("Reading my book"));
    }
    public void readMyBook(Readable p)
    {
        p.read();
    }
}

When you run above program, you will get below output:
Reading my book

As you can see, since Readable has only one abstract method called read(), we were able to call it using lambda expression.
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook