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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP