在Java中,可以通過構造方法、普通方法或直接賦值的方式給類的屬性賦值。
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;
}
在實際應用中,一般會結合構造方法和普通方法來給類的屬性賦值,以保證對象在實例化后能夠具有初始的有效狀態。