Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Sự khác biệt giữa Constructor và Method trong Java

Constructor là phương thức đặc biệt để khởi tạo object. Method là khối code thực hiện hành động/phép tính cụ thể.

Bảng so sánh

STTTiêu chíConstructorMethod
1 Mục đích Tạo và khởi tạo object (allocate memory, set initial state). Thực thi logic nghiệp vụ, tính toán, thay đổi state, trả về giá trị.
2 Gọi (Invocation) Gọi ngầm định (implicit) bởi JVM khi dùng new. Gọi tường minh (explicit) trong code: obj.method().
3 Khi nào gọi Khi từ khóa new được thực thi (hoặc reflection newInstance()). Khi code gọi tên method.
4 Kiểu trả về Không có kiểu trả về (không viết void). Bắt buộc có kiểu trả về (void hoặc type cụ thể).
5 Object tồn tại Khởi tạo object chưa tồn tại. Được gọi trên object đã tồn tại.
6 Tên Trùng tên class (bắt buộc). Không được trùng tên class (convention: camelCase).
7 Kế thừa Không được kế thừa. Subclass tự định nghĩa constructor. Được kế thừa (nếu không private). Có thể override.
8 Overloading Có (multiple constructors). Có (multiple methods cùng tên, khác tham số).
9 Chaining this(...) gọi constructor khác cùng class. super(...) gọi constructor cha. Gọi method khác bình thường.
10 Modifier Không có static, abstract, final, synchronized, native, strictfp. Có thể có tất cả modifier trên.

Ví dụ minh họa

public class JavaTester {
    int num; // instance field
    
    // Constructor
    JavaTester() {
        num = 3;
        System.out.println("Constructor invoked. num: " + num);
    }
    
    // Constructor overloading
    JavaTester(int initialNum) {
        this.num = initialNum;
        System.out.println("Parameterized constructor. num: " + num);
    }
    
    // Instance method
    public void init() {
        num = 5;
        System.out.println("Method invoked. num: " + num);
    }
    
    // Static method
    public static void staticHelper() {
        System.out.println("Static method");
    }
    
    public static void main(String args[]) {
        // Gọi constructor qua new
        JavaTester tester1 = new JavaTester();       // num = 3
        JavaTester tester2 = new JavaTester(100);    // num = 100
        
        // Gọi method tường minh
        tester1.init();                              // num = 5
        tester2.init();                              // num = 5
        
        // Gọi static method
        JavaTester.staticHelper();
    }
}

Kết quả

Constructor invoked. num: 3
Parameterized constructor. num: 100
Method invoked. num: 5
Method invoked. num: 5
Static method

Constructor Chaining (this() / super())

class Parent {
    Parent() { System.out.println("Parent no-arg"); }
    Parent(String msg) { System.out.println("Parent: " + msg); }
}

class Child extends Parent {
    Child() {
        super("from Child"); // Phải là dòng đầu tiên
        System.out.println("Child no-arg");
    }
    Child(int x) {
        this(); // Gọi constructor khác cùng class - phải dòng đầu
        System.out.println("Child int: " + x);
    }
}

public class ChainDemo {
    public static void main(String[] args) {
        new Child(10);
    }
}

Kết quả

Parent: from Child
Child no-arg
Child int: 10

Lưu ý quan trọng

  • Default constructor: Nếu không định nghĩa constructor nào, compiler tự sinh no-arg constructor. Nếu có constructor có tham số → KHÔNG có default constructor tự động.
  • Constructor không thể static/abstract/final.
  • Constructor không trả về giá trị - nhưng ngầm trả về reference đến object vừa tạo.
  • Reflection: Class.getConstructors(), constructor.newInstance(args).
  • Builder Pattern thay thế constructor nhiều tham số: new Builder().setA(1).setB(2).build().

Factory Method vs Constructor

// Constructor - public, tên cố định
public User(String name, int age) { ... }

// Static Factory Method - tên có ý nghĩa, có thể cache, trả về subtype
public static User createGuest() { return new User("Guest", 0); }
public static User createAdmin(String name) { return new User(name, 99); }

Ưu tiên Static Factory Method (Effective Java Item 1) cho API public.