คำถามสัมภาษณ์ Java เรื่อง Constructor
Constructor เป็นหัวใจของ Object Creation ใน Java ความเข้าใจที่ถูกต้องสำคัญมาก
คำถาม 1: Superclass constructor เรียก Subclass constructor ได้ไหม?
ไม่ได้ Superclass ไม่รู้จัก Subclass การเรียกต้องเป็นทางเดียว: Subclass เรียก Superclass ผ่าน super()
คำถาม 2: สร้าง Object โดยไม่ใช้ new Operator ยังไง?
Class.forName("...").newInstance()(Deprecated Java 9+)Constructor.newInstance()(Reflection)clone()(ต้อง implements Cloneable)- Deserialization (
ObjectInputStream) - Unsafe.allocateInstance() (Internal, not recommended)
- Factory Methods (Static factory methods)
คำถาม 3: กฎในการประกาศ Constructor
- ชื่อต้องตรงกับ Class name ตรงตัว
- ไม่มี return type (แม้ void ก็ไม่มี)
- ไม่สามารถเป็น abstract, static, final, synchronized, native, strictfp ได้
- สามารถเป็น public, protected, default, private ได้
- สามารถ overload ได้ (หลาย constructor ต่าง parameter)
- first statement ต้องเป็น
this(...)หรือsuper(...)(ถ้ามี)
คำถาม 4: Constructor มี Return Type ได้ไหม?
ไม่ได้ Constructor ไม่มี return type หากเขียน public void MyClass() จะกลายเป็น Method ไม่ใช่ Constructor
คำถาม 5: Return Type ใน Constructor → Compile Error หรือ Warning?
Compile-time Error: "Invalid method declaration; return type required" (เพราะถูกตีความว่าเป็น method ไม่มี return type)
คำถาม 6: บังคับต้องประกาศ Constructor เมื่อสร้าง Class?
ไม่บังคับ ถ้าไม่ประกาศ Java จะสร้าง Default No-arg Constructor ให้อัตโนมัติ (public หาก class public)
คำถาม 7: Parameterized Constructor คืออะไร? ประกาศเองได้ไหม?
Constructor ที่รับพารามิเตอร์ สามารถประกาศเองได้ หลาย overload ได้
คำถาม 8: Constructor เป็น Private ได้ไหม?
ได้ ใช้ใน: Singleton Pattern, Factory Methods, Utility Classes (ป้องกัน instantiation)
คำถาม 9: this() และ super() ใช้ใน Method ได้ไหม?
ไม่ได้ ใช้ได้เฉพาะใน Constructor บรรทัดแรกเท่านั้น
คำถาม 10: Default Constructor และ Parameterized Constructor อยู่ด้วยกันได้ไหม?
ได้ เป็น Constructor Overloading แต่ถ้าประกาศ Parameterized Constructor เอง Java จะไม่สร้าง Default Constructor ให้ ต้องเขียนเองถ้าต้องการ
คำถาม 11: มี Protected Constructor ได้ไหม?
ได้ ใช้เมื่อ: Subclass ใน package อื่นต้องการเรียก, Factory pattern ใน hierarchy
คำถาม 12: Constructor Overload ได้ไหม? ทำไมต้องการ?
ได้ ใช้เมื่อ: ต้องการสร้าง object หลายวิธี, Default values, Backward compatibility, Builder pattern alternative
คำถาม 13: มี Static Constructor ได้ไหม?
ไม่มีใน Java (C# มี) ใช้ Static Initialization Block แทน: static { ... }
คำถาม 14: มี Final Constructor ได้ไหม?
ไม่ได้ Constructor ไม่สามารถ override ได้อยู่แล้ว (ไม่ใช่ method) final ไม่มีความหมาย
สรุปตาราง
| Feature | Supported? | Note |
|---|---|---|
| Overloading | ✅ | Multiple constructors |
| Private | ✅ | Singleton, Utility |
| Protected | ✅ | Subclass access |
| Default (no-arg) | Auto | Only if no other constructor |
| Return type | ❌ | Becomes method |
| Static | ❌ | Use static block |
| Final | ❌ | Not inheritable anyway |
| Abstract | ❌ | Constructor not inherited |
| this()/super() | First line only | In constructor only |