Functional Interface in java: – A Functional interface Can Consist of Exactly One Incomplete Method in it.
Functional Interface in java
Example 1
@FunctionalInterface
public interface A { // Correct
public void test();
}
Example 2
@FunctionalInterface
public interface A { // Error
public void test1();
public void test2();
}
Note – Functional Interface Was Introduced in Version 8 of java.
- Functional Interfaces Can Be Implemented by a Lambda Expression.
- We Cannot do Multiple inheritances on the Functional Interface.
- We Can Create Any No. of Complete Methods inside Functional Interface.
Default keyword in java
- Using the default keyword we create a complete method in an interface.
- this feature was introduced in version 8 of java.
public interface A{
public void test1();
default void test2() {
System.out.println(100);
}
}
public class B implements A{
@Override
public void test1() {
System.out.println(200);
}
public static void main(String[] args) {
B b1 = new B();
b1.test1();
b1.test2();
}
}
Output:
200
100
You Also Learn –
- What is Abstract Class in Java
- What is Lambda Expression in Java 8
- What is Exception Handling in Java
- Types of Exceptions in Java
- What is inheritance in Java
- What is the Final Keyword in Java
- What is Interface in Java
- What is Wrapper Class in Java
- Break Keywords in Java with Example
- What is Method In Java With Example
- What is Constructor in Java With Example
- What is Polymorphism in java
- What is a non-static variable in java
- Types of access specifiers in java
- What is the local variable in java
- Types of loops in java with program
- Remove duplicate elements in an Array in java
- What is var type in java
- What is a static variable in java
- What is the difference between return and return value?
- What is this keyword in java
Note 1 – We can create any number of complete methods inside the functional interface.
@FunctionalInterface
public interface A{
public void test1();
default void test2(){
System.out.println(200);
}
default void test3() {
System.out.println(300);
}
}
public class B implements A{
@Override
public void test1() {
System.out.println(100);
}
public static void main(String[] args) {
B b1 = new B();
b1.test1();
b1.test2();
b1.test3();
}
}
Output:
100
200
300
Note 2 – We can not do multiple inheritances on the functional interface.