java構(gòu)造函數(shù)怎樣初始化對(duì)象

小樊
81
2024-09-21 05:22:46

在Java中,構(gòu)造函數(shù)是一種特殊的方法,用于初始化對(duì)象的狀態(tài)。構(gòu)造函數(shù)的名稱與類名相同,沒(méi)有返回類型。當(dāng)創(chuàng)建類的對(duì)象時(shí),構(gòu)造函數(shù)會(huì)被自動(dòng)調(diào)用。以下是使用構(gòu)造函數(shù)初始化對(duì)象的幾種方法:

  1. 默認(rèn)構(gòu)造函數(shù):如果類中沒(méi)有定義任何構(gòu)造函數(shù),編譯器會(huì)自動(dòng)為類提供一個(gè)默認(rèn)構(gòu)造函數(shù)。這個(gè)默認(rèn)構(gòu)造函數(shù)沒(méi)有參數(shù),也沒(méi)有執(zhí)行任何操作。
public class Person {
    private String name;
    private int age;

    // 默認(rèn)構(gòu)造函數(shù)
    public Person() {
        this.name = "";
        this.age = 0;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person(); // 調(diào)用默認(rèn)構(gòu)造函數(shù)
    }
}
  1. 參數(shù)化構(gòu)造函數(shù):可以在構(gòu)造函數(shù)中添加參數(shù),以便在創(chuàng)建對(duì)象時(shí)傳遞值。
public class Person {
    private String name;
    private int age;

    // 參數(shù)化構(gòu)造函數(shù)
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person("John", 30); // 調(diào)用參數(shù)化構(gòu)造函數(shù)
    }
}
  1. 委托構(gòu)造函數(shù):在一個(gè)構(gòu)造函數(shù)中調(diào)用另一個(gè)構(gòu)造函數(shù),以便重用代碼。這需要使用this()關(guān)鍵字。
public class Person {
    private String name;
    private int age;

    // 默認(rèn)構(gòu)造函數(shù)
    public Person() {
        this("", 0); // 調(diào)用參數(shù)化構(gòu)造函數(shù)
    }

    // 參數(shù)化構(gòu)造函數(shù)
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person(); // 調(diào)用默認(rèn)構(gòu)造函數(shù)
        Person person2 = new Person("John", 30); // 調(diào)用參數(shù)化構(gòu)造函數(shù)
    }
}
  1. 使用final關(guān)鍵字:如果類的實(shí)例一旦創(chuàng)建就不能被修改,可以使用final關(guān)鍵字修飾構(gòu)造函數(shù)。
public final class Person {
    private final String name;
    private final int age;

    // 參數(shù)化構(gòu)造函數(shù)
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            Person person = new Person("John", 30); // 調(diào)用參數(shù)化構(gòu)造函數(shù)
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

0