English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à transmettre des méthodes à d'autres méthodes en Java
Pour comprendre cet exemple, vous devriez comprendre ce qui suitProgrammation JavaThème :
class Main { //Calculer la somme public int add(int a, int b) { //Calculer la somme 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 has become easier in Java. For more information, please visitJava Lambda expressions as method parameters.