ในบทความนี้ เราจะทำความเข้าใจวิธี เรียก Constructor หนึ่งจากอีก Constructor หนึ่งในคลาสเดียวกัน โดยใช้คำสั่ง this()
หลักการ: this(พารามิเตอร์...) ต้องเป็นคำสั่งแรกใน Constructor จะเรียก Constructor อื่นที่มีลายเซ็นตรงกัน
ตัวอย่าง Input และ Output
Input:
The numbers are defined as 12 and 30
Output:
The sum is: 42 The product is: 360
อัลกอริธึม
ขั้นตอนที่ 1 - เริ่มต้น ขั้นตอนที่ 2 - ประกาศตัวแปร my_sum หรือ my_product ขั้นตอนที่ 3 - ใน Constructor เริ่มต้น ใช้ this(12, 30) เรียก Constructor ที่รับ 2 พารามิเตอร์ ขั้นตอนที่ 4 - Constructor ที่ 2 คำนวณผลบวกหรือผลคูณเก็บไว้ ขั้นตอนที่ 5 - สร้างเมธอด display() แสดงผล ขั้นตอนที่ 6 - ใน main สร้างออบเจกต์และเรียก display()
ตัวอย่างที่ 1: คำนวณผลบวก (Sum)
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();
}
}
Output
The numbers are defined as 12 and 30 The sum is: 42
ตัวอย่างที่ 2: คำนวณผลคูณ (Product)
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();
}
}
Output
The numbers are defined as 12 and 30 The product of the two values is: 360