이 기사에서는 메소드 호출을 다른 메소드에 인수로 전달하는 방법을 이해할 것입니다. 다른 클래스 내부에 해당 클래스의 객체를 생성함으로써 다른 클래스의 메소드를 호출할 수 있습니다. 객체 생성 후 객체 참조 변수를 이용하여 메소드를 호출한다.
아래는 동일한 데모입니다 -
입력
입력이 -
라고 가정합니다.Enter two numbers : 2 and 3
출력
원하는 출력은 -
The cube of the sum of two numbers is: 125
알고리즘
Step 1 - START Step 2 - Declare two variables values namely my_input_1 and my_input_2 Step 3 - We define a function that takes two numbers, and returns their sum. Step 4 - We define another function that takes one argument and multiplies it thrice, and returns the output. Step 5 - In the main function, we create a new object of the class, and create a Scanner object. Step 6 - Now, we can either pre-define the number or prompt the user to enter it. Step 7 - Once we have the inputs in place, we invoke the function that returns the cube of the input. Step 8 - This result is displayed on the console.
예시 1
여기에서 입력은 프롬프트에 따라 사용자가 입력하고 있습니다. 우리코딩 그라운드 도구에서 이 예제를 라이브로 사용해 볼 수 있습니다.
.
import java.util.Scanner;
public class Main {
public int my_sum(int a, int b) {
int sum = a + b;
return sum;
}
public void my_cube(int my_input) {
int my_result = my_input * my_input * my_input;
System.out.println(my_result);
}
public static void main(String[] args) {
Main obj = new Main();
int my_input_1, my_input_2;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter the first number : ");
my_input_1 = my_scanner.nextInt();
System.out.print("Enter the second number : ");
my_input_2 = my_scanner.nextInt();
System.out.println("The cube of the sum of two numbers is: ");
obj.my_cube(obj.my_sum(my_input_1, my_input_2));
}
} 출력
Required packages have been imported A reader object has been defined Enter the first number : 2 Enter the second number : 3 The cube of the sum of two numbers is: 125
예시 2
여기서 정수는 이전에 정의되었으며 그 값은 콘솔에 액세스되어 표시됩니다.
public class Main {
public int my_sum(int a, int b) {
int sum = a + b;
return sum;
}
public void my_cube(int my_input) {
int my_result = my_input * my_input * my_input;
System.out.println(my_result);
}
public static void main(String[] args) {
Main obj = new Main();
int my_input_1, my_input_2;
my_input_1 = 3;
my_input_2 = 2;
System.out.println("The two number is defined as " +my_input_1 +" and " +my_input_2);
System.out.println("The cube of the sum of two numbers is: ");
obj.my_cube(obj.my_sum(my_input_1, my_input_2));
}
} 출력
The two number is defined as 3 and 2 The cube of the sum of two numbers is: 125