Java 程序从另一个调用一个构造函数


在本文中,我们将了解如何从另一个调用一个构造函数。关键字“this()”用于调用一个构造函数。

以下是相同的演示。我们将使用 this() 显示两个数字的和与乘积 −

输入

假设我们的输入是 −

The numbers are defined as 12 and 30

输出

所需的输出将是 −

The sum is: 42
The product is: 360

算法

Step 1 - START
Step 2 - Declare an integer value namely my_sum
Step 3 - In the main class, we define a ‘this’ reference to the numbers which would be used as input.
Step 4 - This will call the ‘this’ constructor that invokes the current class constructor.
Step 5 - Another ‘display’ function is used to display the sum.
Step 6 - An object of the class is created, and the functions are invoked to display the result

示例 1

在此处正在计算两个数字的和。

public class Main {
   int my_sum;
   Main() {
      this(12, 30);
   }
   Main(int my_input_1, int my_input_2) {
      System.out.println("The numbers are defined as " +my_input_1 +" and " +my_input_2);
      this.my_sum = my_input_1 + my_input_2;
   }
   void display() {
      System.out.println("The sum is: " + my_sum);
   }
   public static void main(String[] args) {
      Main my_object = new Main();
      my_object.display();
   }
}

输出

The numbers are defined as 12 and 30
The sum is: 42

示例 2

在此处正在计算两个数字的乘积。

public class Main {
   int my_product;
   Main() {
      this(12, 30);
   }
   Main(int my_input_1, int my_input_2) {
      System.out.println("The numbers are defined as " +my_input_1 +" and " +my_input_2);
      this.my_product = my_input_1 * my_input_2;
   }
   void display() {
      System.out.println("The product of the two values is: " + my_product);
   }
   public static void main(String[] args) {
      Main my_object = new Main();
      my_object.display();
   }
}

输出

The numbers are defined as 12 and 30
The product of the two values is: 360

更新于: 22-Feb-2022

356 次浏览

开启你的 职业

完成课程获得认证

开始学习
广告