在Java中,可以通過構(gòu)造方法、普通方法或直接賦值的方式給類的屬性賦值。
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Person {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
public class Person {
private String name = "Alice";
private int age = 25;
}
在實(shí)際應(yīng)用中,一般會結(jié)合構(gòu)造方法和普通方法來給類的屬性賦值,以保證對象在實(shí)例化后能夠具有初始的有效狀態(tài)。