English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Neste exemplo, vamos aprender a passar métodos como parâmetros para outros métodos no Java
Para entender este exemplo, você deve saber o seguinteProgramação JavaTema:
class Main { //Calcular a soma public int add(int a, int b) { //Calcular a soma int sum = a + b; return sum; } //Calculate square public void square(int num) { int result = num * num; System.out.println(result); // prints 576 } public static void main(String[] args) { Main obj = new Main(); // Calling the square() method // Passing add() as a parameter obj.square(obj.add(15, 9)); } }
In the above example, we created two methods named square() and add(). Note this line,
obj.square(obj.add(15, 9));
Here, we are calling the square() method. The square() method takes the add() method as its parameter.
With the introduction of lambda expressions, passing methods as parameters in Java has become easier. For more information, please visitJava Lambda expressions as method parameters.