在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;
}
在实际应用中,一般会结合构造方法和普通方法来给类的属性赋值,以保证对象在实例化后能够具有初始的有效状态。