Constructor เรียกตอนสร้างอ็อบเจกต์ Initialize instance variables ชื่อตรงคลาส ไม่มี return type
มี 2 ประเภทหลัก:
- Parameterized Constructors - รับพารามิเตอร์
- No-arg Constructors - ไม่รับพารามิเตอร์ (Default Constructor)
1. Parameterized Constructor
รับพารามิเตอร์ Initialize instance variables ด้วยค่าที่ส่งมา
import java.util.Scanner;
public class Test {
int num;
String data;
float flt;
Test(int num, String data, float flt) {
this.num = num;
this.data = data;
this.flt = flt;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer value: ");
int num = sc.nextInt();
System.out.println("Enter a string value: ");
String data = sc.next();
System.out.println("Enter a floating point value: ");
float flt = sc.nextFloat();
Test obj = new Test(num, data, flt);
System.out.println(obj.num);
System.out.println(obj.data);
System.out.println(obj.flt);
}
}
Output
Enter an integer value: 1024 Enter a string value: test Enter a floating point value: 11.2 1024 test 11.2
2. No-arg Constructor (Default Constructor)
ไม่รับพารามิเตอร์ ตั้งค่า default เอง หรือให้ compiler สร้าง (ถ้าไม่มี constructor อื่น)
public class Test {
int num;
String data;
float flt;
Test() {
this.num = 100;
this.data = "test";
this.flt = 125.33f;
}
public static void main(String args[]) {
Test obj = new Test();
System.out.println(obj.num);
System.out.println(obj.data);
System.out.println(obj.flt);
}
}
Output
100 test 125.33
⚠️ กฎสำคัญ: Default Constructor ถูกสร้างโดย Compiler ก็ต่อเมื่อ
- ไม่มี Constructor ใดๆ ถูกประกาศในคลาส
- ถ้าเขียน Constructor เองแม้เพียง 1 ตัว → Compiler ไม่สร้าง Default Constructor ให้
Constructor Overloading (หลาย Constructor ในคลาสเดียว)
public class Demo {
private int x;
private String y;
// No-arg
public Demo() { this(0, "default"); }
// Parameterized - 1 param
public Demo(int x) { this(x, "default"); }
// Parameterized - 1 param (String)
public Demo(String y) { this(0, y); }
// Parameterized - 2 params (Primary)
public Demo(int x, String y) {
this.x = x;
this.y = y;
}
}