Interview question
What is a functional interface in Java? Java में functional interface क्या है?
Answer
A functional interface is an interface with EXACTLY ONE abstract method, making it eligible to be implemented using a lambda expression. The @FunctionalInterface annotation enforces this at compile time.
@FunctionalInterface
interface Calculator {
int calculate(int a, int b); // exactly one abstract method
// default and static methods are allowed, don't count against the 'one method' rule
default void printInfo() {
System.out.println('Calculator interface');
}
}
Calculator add = (a, b) -> a + b;
Calculator multiply = (a, b) -> a * b;
System.out.println(add.calculate(3, 4)); // 7
System.out.println(multiply.calculate(3, 4)); // 12
// @FunctionalInterface catches mistakes at compile time
// @FunctionalInterface
// interface Broken {
// void method1();
// void method2(); // COMPILE ERROR - more than one abstract method
// }
// Java's built-in functional interfaces (java.util.function package)
Function<Integer, Integer> square = x -> x * x; // takes T, returns R
Predicate<Integer> isEven = x -> x % 2 == 0; // takes T, returns boolean
Consumer<String> printer = s -> System.out.println(s); // takes T, returns nothing
Supplier<String> greeting = () -> 'Hello'; // takes nothing, returns T
BiFunction<Integer, Integer, Integer> add2 = (a, b) -> a + b; // two inputs, one output
System.out.println(square.apply(5)); // 25
System.out.println(isEven.test(4)); // true
printer.accept('Hello World'); // Hello World
System.out.println(greeting.get()); // HelloFunctional interface exactly एक abstract method वाला interface है, जो lambda expression से implement होने योग्य बनाता है। @FunctionalInterface annotation इसे compile time पर enforce करता है।
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
default void printInfo() {
System.out.println('Calculator interface');
}
}
Calculator add = (a, b) -> a + b;
Calculator multiply = (a, b) -> a * b;
System.out.println(add.calculate(3, 4)); // 7
System.out.println(multiply.calculate(3, 4)); // 12
// Java के built-in functional interfaces
Function<Integer, Integer> square = x -> x * x;
Predicate<Integer> isEven = x -> x % 2 == 0;
Consumer<String> printer = s -> System.out.println(s);
Supplier<String> greeting = () -> 'Hello';
BiFunction<Integer, Integer, Integer> add2 = (a, b) -> a + b;
System.out.println(square.apply(5)); // 25
System.out.println(isEven.test(4)); // true
printer.accept('Hello World');
System.out.println(greeting.get()); // HelloWas this answer clear?