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

Constructor ใน Java ใช้ทำอะไร


Constructor เรียกตอนสร้างอ็อบเจกต์ Initialize instance variables ชื่อตรงคลาส ไม่มี return type

2 ประเภท: Parameterized และ No-arg จุดประสงค์หลัก: Initialize Instance Variables

ตัวอย่างที่ 1: No-arg Constructor Initialize ค่าคงที่

public class Test {
    int num;
    String data;
    
    Test() {
        num = 100;
        data = "sample";
    }
    
    public static void main(String args[]) {
        Test obj = new Test();
        System.out.println(obj.num);
        System.out.println(obj.data);
    }
}

Output

100
sample

ตัวอย่างที่ 2: Parameterized Constructor Initialize ค่า Dynamic

import java.util.Scanner;

public class Test {
    int num;
    String data;
    
    Test(int num, String data) {
        this.num = num;
        this.data = data;
    }
    
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string value: ");
        String data = sc.nextLine();
        System.out.println("Enter an integer value: ");
        int num = sc.nextInt();
        
        Test obj = new Test(num, data);
        System.out.println(obj.num);
        System.out.println(obj.data);
    }
}

Output

Enter a string value: sample
Enter an integer value: 1023
1023
sample

Constructor ใช้ทำอะไรเพิ่มเติม?

  • Validation - ตรวจสอบค่า input ก่อน assign
  • Dependency Injection - รับ dependencies ผ่าน constructor
  • Resource Acquisition - เปิดไฟล์, connection (แต่ควรใช้ try-with-resources)
  • Immutable Objects - กำหนด final fields ครั้งเดียว
  • Builder Pattern - Private constructor + static factory methods

Constructor Chaining (this() และ super())

public class Example {
    private int x;
    private String y;
    
    // Primary constructor
    public Example(int x, String y) {
        this.x = x;
        this.y = y;
    }
    
    // Convenience constructors - delegate to primary
    public Example(int x) {
        this(x, "default");
    }
    
    public Example(String y) {
        this(0, y);
    }
    
    public Example() {
        this(0, "default");
    }
    
    // Superclass constructor
    public Example(int x, String y, double z) {
        super();  // เรียก parent constructor (optional ถ้าเป็น no-arg)
        this.x = x;
        this.y = y;
        // z ใช้ใน subclass
    }
}