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

วิธีสร้าง Parameterized Constructor ใน Java


Parameterized Constructor รับพารามิเตอร์เพื่อกำหนดค่าเริ่มต้นให้ Instance Variables ตอนสร้างอ็อบเจกต์ ช่วยให้ตั้งค่าได้แบบ Dynamic

ตัวอย่างครบครัน: Multiple Constructors (Constructor Overloading)

import java.util.Scanner;

public class StudentData {
    private String name;
    private int age;
    
    // 1. Parameterized constructor (ทั้งคู่)
    public StudentData(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // 2. Default constructor - เรียก constructor อื่นด้วย this()
    public StudentData() {
        this(null, 0);
    }
    
    // 3. Constructor รับแค่ name
    public StudentData(String name) {
        this(name, 0);
    }
    
    // 4. Constructor รับแค่ age
    public StudentData(int age) {
        this(null, 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();
        
        System.out.println("\n--- Constructor ทั้งคู่ ---");
        new StudentData(name, age).display();
        
        System.out.println("\n--- Constructor แค่ name ---");
        new StudentData(name).display();
        
        System.out.println("\n--- Constructor แค่ age ---");
        new StudentData(age).display();
        
        System.out.println("\n--- Default Constructor ---");
        new StudentData().display();
    }
}

ผลลัพธ์

Enter the name of the student: Krishna
Enter the age of the student: 22

--- Constructor ทั้งคู่ ---
Name of the Student: Krishna
Age of the Student: 22

--- Constructor แค่ name ---
Name of the Student: Krishna
Age of the Student: 0

--- Constructor แค่ age ---
Name of the Student: null
Age of the Student: 22

--- Default Constructor ---
Name of the Student: null
Age of the Student: 0

Key Points

  • ใช้ this(...) เรียก constructor อื่นในคลาสเดียวกัน (ต้องเป็นคำสั่งแรก)
  • ลดโค้ดซ้ำ (DRY) - logic การกำหนดค่าอยู่ที่ constructor "หลัก" ตัวเดียว
  • เรียกได้ด้วย new ClassName(args) ตอน instantiate

Constructor vs Method

คุณสมบัติConstructorMethod
ชื่อตรงกับคลาสอะไรก็ได้ (camelCase)
Return typeไม่มีต้องมี (void หรือ type)
การเรียกnew ClassName()obj.methodName()
Inheritanceไม่สืบทอด (แต่ super() เรียก parent)สืบทอดได้ (override)