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

javaobject oriented programmingprogramming更新于 2024/4/15 14:36:17

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

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

输入

假设我们的输入是 −

数字定义为 12 和 30

输出

所需的输出将是 −

总和为:42
乘积为:360

算法

步骤 1 - 开始
步骤 2 - 声明一个整数值,即 my_sum
步骤 3 - 在主类中,我们定义一个 ‘this’ 引用将用作输入的数字。
步骤 4 - 这将调用 ‘this’ 构造函数,该构造函数调用当前类构造函数。
步骤 5 - 使用另一个"display"函数显示总和。
步骤 6 - 创建类的对象,并调用函数显示结果

示例 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

相关文章


有用资源