Home > Java > javaTutorial > What\'s the Best Way to Simulate Function Pointers in Java?

What\'s the Best Way to Simulate Function Pointers in Java?

Linda Hamilton
Release: 2024-12-02 19:57:10
Original
895 people have browsed it

What's the Best Way to Simulate Function Pointers in Java?

Nearest Alternative to Function Pointers in Java

Java lacks function pointers, presenting a challenge when creating methods that perform similar tasks with minor variations. To address this, a suitable alternative is using anonymous inner classes.

Anonymous Inner Class Solution

An anonymous inner class allows you to define a method without creating a separate named class. It follows the pattern of defining an interface with the required method and implementing it in an anonymous inner class.

For example, consider a method that takes a string as a parameter and returns an integer. First, define an interface:

interface StringFunction {
    int func(String param);
}
Copy after login

A method that accepts a pointer to this function would look like this:

public void takingMethod(StringFunction sf) {
   int i = sf.func("my string");
   // do whatever ...
}
Copy after login

To call this method, create an anonymous inner class implementing the interface:

ref.takingMethod(new StringFunction() {
    public int func(String param) {
        // body
    }
});
Copy after login

Alternatively, Java 8 introduces lambda expressions, which provide a more concise syntax for this purpose:

ref.takingMethod(param -> bodyExpression);
Copy after login

The above is the detailed content of What\'s the Best Way to Simulate Function Pointers in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template