A functional interface in Java is an interface that has only one abstract method, making it suitable for use with lambda expressions and method references (introduced in Java 8).
- Use
@_FunctionalInterface_ to ensure only one abstract method (annotation is optional). - Enable clean, concise code using lambdas and method references.
Meaning of Method Reference
- A method reference is simply a shortcut syntax for a lambda expression.
- When a lambda expression is only calling an existing method, instead of writing the full lambda, you can directly refer to that method.
Syntax looks like:
ClassName::staticMethodName
objectReference::instanceMethodName
ClassName::new (for constructors)
Types of MethodReference:
Example 1: Static Method Reference
import java.util.function.Function;
public class MethodRefDemo {
public static int square(int n) {
return n * n;
}
public static void main(String[] args) {
// Lambda style
Function<Integer, Integer> f1 = n -> MethodRefDemo.square(n);
// Method reference style
Function<Integer, Integer> f2 = MethodRefDemo::square;
System.out.println(f1.apply(5)); // 25
System.out.println(f2.apply(6)); // 36
}
}
Example 2: Instance Method Reference
import java.util.function.Consumer;
public class MethodRefDemo2 {
public void printMsg(String msg) {
System.out.println(msg);
}
public static void main(String[] args) {
MethodRefDemo2 obj = new MethodRefDemo2();
// Lambda style
Consumer<String> c1 = s -> obj.printMsg(s);
// Method reference style
Consumer<String> c2 = obj::printMsg;
c1.accept("Hello Lambda");
c2.accept("Hello Method Reference");
}
}
Example 3: Constructor Reference
import java.util.function.Supplier;
class Employee {
Employee() {
System.out.println("Employee object created!");
}
}
public class ConstructorRefDemo {
public static void main(String[] args) {
// Lambda style
Supplier<Employee> s1 = () -> new Employee();
// Constructor reference style
Supplier<Employee> s2 = Employee::new;
s1.get();
s2.get();
}
}
Multiple‑Parameter Constructor
import java.util.function.BiFunction;
class Product {
String name;
double price;
Product(String name, double price) {
this.name = name;
this.price = price;
System.out.println("Product created: " + name + " - " + price);
}
}
public class ConstructorRefDemo3 {
public static void main(String[] args) {
// Lambda style
BiFunction<String, Double, Product> f1 = (n, p) -> new Product(n, p);
// Constructor reference style
BiFunction<String, Double, Product> f2 = Product::new;
f1.apply("Laptop", 75000.0); // Product created: Laptop - 75000.0
f2.apply("Phone", 25000.0); // Product created: Phone - 25000.0
}
}
Thanks for Reading......
That’s it for this blog—see you in the next java8 one!
Top comments (0)