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:
- What are new features which got introduced in Java 8?
- What are main advantages of using Java 8?
- Can you explain the syntax of Lambda expression?
- What are functional interfaces?
- What Is a Default Method and When Do We Use It?