ในบทความนี้ เราจะเข้าใจวิธีการส่งเมธอดเป็นอาร์กิวเมนต์ไปยังเมธอดอื่น เราสามารถเรียกใช้เมธอดจากคลาสอื่นได้โดยการสร้างอ็อบเจ็กต์ของคลาสนั้นภายในคลาสอื่น หลังจากสร้างอ็อบเจ็กต์แล้ว ให้เรียกใช้เมธอดโดยใช้ตัวแปรอ้างอิงอ็อบเจ็กต์
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ป้อนข้อมูล
สมมติว่าข้อมูลที่เราป้อนคือ −
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