Functional Interfaces as Function Pointers in Java
In Java, where function pointers are unavailable, anonymous inner classes or lambda expressions serve as suitable alternatives.
Anonymous Inner Classes
Imagine you need methods that perform similar actions but vary slightly in a single line of computation. To implement this using an anonymous inner class:
interface StringFunction { int func(String param); }
public void takingMethod(StringFunction sf) { int i = sf.func("my string"); // Operations... }
ref.takingMethod(new StringFunction() { public int func(String param) { // Implementation... } });
Lambda Expressions (Java 8 )
Syntactically simpler, you can utilize lambda expressions to achieve the same result:
ref.takingMethod(param -> { // Implementation... });
By utilizing anonymous inner classes or lambda expressions, you can create function pointers in Java, enhancing code reusability and flexibility.
The above is the detailed content of How Can I Simulate Function Pointers in Java Using Anonymous Inner Classes or Lambda Expressions?. For more information, please follow other related articles on the PHP Chinese website!