Tags:

public class MyThisTest {
private int a;

public MyThisTest() {
this(42); // calls the other constructor
}

public MyThisTest(int a) {
this.a = a; // assigns the value of the parameter a to the field of the same name
}

สมมุติผมสร้าง object ขึ้นมา ผมสงสัยว่าถ้าหากมี MyThisTest อีกหนึ่ง constructor จะเกิดอะไรขึ้นครับ

แล้วการสร้่าง constructor ชื่อเดิมๆ หลายตัวมีประโยชน์รึปล่าวครับหรือแทบไม่จำเป็นต้องใช้เลย

Get latest news from Blognone
By: wklk
ContributorAndroid
on 28 June 2012 - 16:35 #438373

constructor สร้างไว้หลาย ๆ ตัวก็ได้นะ ถ้าคิดว่าต้องใช้

เช่นตัวอย่างนี้

public class Car { private int seat; private int wheel;

public Car(){ seat=4; wheel=4; }

public Car(int a){ seat=a; wheel=4; }

public Car(int a, int b){ seat=a; wheel=b; } }

เวลาใช้งาน ถ้าเราแค่อยากได้รถสักคัน เราก็จะสร้าง object จาก Car() แล้วเราก็จะได้รถ 4 ล้อ 4 ที่นั่ง
แต่ถ้าเมื่อใดที่เราเกิดอยากได้รถ 7 ที่นั่ง ก็สามารถสร้าง object จาก Car(7) ได้
แล้วถ้าเมื่อใดอยากได้รถ 10 ล้อ ก็สามารถสร้าง object จาก Car(2, 10) ได้ เป็นต้น

สรุปว่าสร้าง constructor ไว้เยอะ ๆ ก็เพื่อความยืดหยุ่นในการใช้งานนั่นเอง