Constructor, Chaining และ super
เราสามารถกำหนดค่าเริ่มต้นให้กับ instance ผ่านทาง Constructor มีรูปแบบดังนี้
class A {
int i;
A(int i) {
this.i = i;
}
}
โดยจะต้องชื่อเดียวกันกับ class และสามารถเรียกใช้โดย A a = new A(100);
จาก code ตัวอย่าง ทำให้เราไม่สามารถ new A(); หรือใช้ Empty Constructor ได้
ซึ่ง Empty Constructor นั้นกรณีที่ class เราไม่มี constructor Compiler จะ generate
Empty Constructor ซึ่งมี modifier เป็น public ให้โดยอัตโนมัติ เช่น
class A {}
เป็น
class A{public A(){}}
แต่ Empty Constructor จะไม่ถูก generate ให้ หากที่เรามี constructor ให้ class
อย่างน้อยหนึ่งตัว
constructor สามารถใส่ modifier ได้ บางครั้งการเขียนโปรแกรมระดับสูงเราจะได้เห็น
private constructor ก็ได้ และ constructor ก็สามารถ overload ได้เช่นกัน เช่น
class A {
A(int i){}
A(String s){}
A(Double d){}
}
การออกแบบที่ดีควรมี constructor ที่เป็นปลายทางไว้เก็บค่าหรือ initialize ต่างๆตัว
เดียวแล้วให้ constructor ตัวอื่นเป็นตัวเรียก โดยใช้ keyword this(..) เช่น
class Human {
int age;
String name;
Human(int age, String name) {
this.age = age;
this.name = name;
}
Human(int age) {
this(age, "");
}
Human(String name) {
this(0, name);
}
Human() {
this(0, "");
}
}
การใช้ this จะต้องอยู่บรรทัดบนสุด และมีได้แค่ statement ใน constructor นั้น
Chaining Constructor
นอกจาก Compiler จะแอบสร้าง Empty Constructor ให้เรากรณีที่มี constructor ใดๆ
เลยแล้ว ยังจะแอบแทรก statement super(); ที่ทำหน้าที่ไปเรียก Empty constructor กรณีที่มีของ super class ให้เราด้วย ลองดูตัวอย่างครับ
class A {
A() {
System.out.println("A");
}
}
class B extends A {
}
จากนั้นลอง new B(); จะพบว่า constructor ของ A จะถูกเรียกเหมือนกับว่า code
เป็นดังนี้
class B extends A {
public B() {
super();
}
}
ลองดูอีกตัวอย่างครับ
class A {
A() {
System.out.println("A");
}
}
class B extends A {
B() {
System.out.println("B");
}
}
class C extends B {
C() {
System.out.println("C");
}
}
ผลลัพท์ที่ได้หาก new C(); คือ
A
B
C
ถ้าหาก super class ไม่มี Empty Constructor นั้น เราต้องมาระบุ super(..) เองเช่น
class A {
A (int i){}
}
class B {
B() {
super(9);
}
}
ซึ่งก็เหมือนกับ this(..) คือต้องวางอยู่บรรทัดแรกและมีัไ้ด้แค่อันเดียว ส่วนความ
สัมพันธ์ระหว่าง super(..) และ this(..) คือถ้ามี super ก็ห้ามมี this ถ้ามี this ก็ห้ามมี
super ครับ ลองดูอีกซํกตัวอย่าง
class Human {
int age;
String name;
Human(int age, String name) {
this.age = age;
this.name = name;
}
Human(int age) {
this(age, "");
}
Human(String name) {
this(0, name);
}
Human() {
this(0, "");
}
}
class Student extends Human {
String id;
String(String id, int age, String name) {
super(age, name);
this.id = id;
}
String(int age, String name) {
this("", age, name);
}
String(int age) {
this("", age, "");
}
String(String name) {
this("", 0, name);
}
Student() {
this("", 0, "");
}
}
ไม่มีความเห็น