Warning: Undefined array key "amp-addthis" in /home/tgagmvup/onlinestudy.guru/wp-content/plugins/addthis/backend/AddThisSharingButtonsFeature.php on line 101
lang="en-US"> @Functional Interface in Java - onlinestudy.guru
Site icon onlinestudy.guru

@Functional Interface in Java

Que 1. What is FunctionalInterface in Java?

A functional interface is an annotation in Java introduced in JDK 8.

Found in java.util.function package 

The functional interface exactly contains only one abstract method.
Single Abstract Method 
Lambda Expression and Method reference
Readability and concise

When to use @FunctionalInterface
Use when you want concise code and want to use lambda expression or stream operation in that case we can go for @FunctionInterface. 

To represent the instance of a functional interface lambda expressions are used.

What happens if you define more than one abstract method in @FunctionalInterface
If you are going to define more than one abstract method in a functional interface you will get compilation errors. 

All methods inside the interface are abstract by default. 

Only one abstract and n number of static and default methods can be defined under the functional interface. 

What are some commonly used types of functional interfaces?

  1. Consumer:- argument accepted but did not return anything. 
  2. Predicate:- Perform the test and return a boolean value.
  3. Supplier: does not take any argument but returns value.
  4. Function:- transfer argument into returnable value. 

Why is a functional interface introduced in Java?

  1. Allow users to use lambda expressions.
  2. It allows users to use functional programming. 
  3. The functional interface ensures that there is only one abstract method. 
  4. Before java8, we had to implement these interfaces or create anonymous inner classes to implement methods.

Can a functional interface inherit/implement another interface?

A functional interface can’t extend and inherit another interface if it contains an abstract method.

However, a functional interface can be inherited if it contains only static and default methods in it.

If we have used @FunctionalInterface  but did not declare any abstract method what will happen? 

It will throw a compile-time error. Indicating that the target method is not found or no abstract method is found in the interface.

Exit mobile version