Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ประโยชน์ของ Parameterized Constructor ใน Java


Constructor เรียกตอนสร้างอ็อบเจกต์ Initialize instance variables มี 2 ประเภท: Parameterized และ No-arg

จุดประสงค์หลักของ Parameterized Constructor

Initialize Instance Variables แบบ Dynamic ด้วยค่าที่ระบุตอนสร้างอ็อบเจกต์ (Instantiation Time)

Syntax

public class Sample {
    int i;
    public Sample(int i) {
        this.i = i;
    }
}

ตัวอย่าง: Student Class กับ Parameterized Constructor

import java.util.Scanner;

public class StudentData {
    private String name;
    private int age;
    
    // Parameterized Constructor
    public StudentData(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public void display() {
        System.out.println("Name of the Student: " + this.name);
        System.out.println("Age of the Student: " + this.age);
    }
    
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the name of the student: ");
        String name = sc.nextLine();
        System.out.println("Enter the age of the student: ");
        int age = sc.nextInt();
        
        // เรียก Parameterized Constructor
        new StudentData(name, age).display();
    }
}

Output

Enter the name of the student: Sundar
Enter the age of the student: 20
Name of the Student: Sundar
Age of the Student: 20

ทำไมต้องใช้ Parameterized Constructor?

ไม่ใช้ (Setters)ใช้ Parameterized Constructor
Object สร้างเสร็จ → "Incomplete state"Object "Complete" ตั้งแต่เกิด
ต้อง call setters หลายครั้งSingle statement: new Class(val1, val2)
Mutable - เปลี่ยนค่าได้ตลอดทำให้เป็น Immutable ได้ (final fields)
Thread-unsafe ระหว่างการ setThread-safe (immutable)
Validation 分散Validation รวมอยู่ใน Constructor

Best Practice: Immutable Objects

public final class Student {
    private final String name;
    private final int age;
    
    public Student(String name, int age) {
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("Name cannot be empty");
        }
        if (age < 0 || age > 150) {
            throw new IllegalArgumentException("Invalid age");
        }
        this.name = name;
        this.age = age;
    }
    
    // Getters only - no setters
    public String getName() { return name; }
    public int getAge() { return age; }
}