Home > Java > javaTutorial > How Can Functions Be Passed as Parameters in Java?

How Can Functions Be Passed as Parameters in Java?

Mary-Kate Olsen
Release: 2024-12-12 22:08:13
Original
1041 people have browsed it

How Can Functions Be Passed as Parameters in Java?

Passing Functions as Parameters in Java

In Java, one can leverage Java 8's lambda expressions to pass a function as an argument. When working with interfaces containing a single abstract method (SAM types), lambda expressions can be substituted, allowing for concise code. For instance:

interface MyInterface {
    String doSomething(int param1, String param2);
}

MyInterface myInterface = (p1, p2) -> { return p2 + p1; };
Copy after login

Alternatively, method references can provide even cleaner syntax:

new Thread(this::someMethod).start();
Copy after login

Pre-Java 8 Approach

Prior to Java 8, the Command Pattern was commonly used to pass functions as arguments. This involved wrapping the function in an interface like Callable:

public T myMethod(Callable<T> func) {
    return func.call();
}
Copy after login

For example:

public int methodToPass() { return 3; }

public void dansMethod(int i, Callable<Integer> myFunc) { }
Copy after login

To call the function, an anonymous inner class would be used:

dansMethod(100, new Callable<Integer>() {
   public Integer call() {
        return methodToPass();
   }
});
Copy after login

Remember that this approach is essentially equivalent to function pointers in other languages.

The above is the detailed content of How Can Functions Be Passed as Parameters 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