在Java中,實體類對象賦值的方法可以通過以下幾種方式實現:
public class Person {
private String name;
private int age;
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", 20);
}
}
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 Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("John");
person.setAge(20);
}
}
public class Person {
public String name;
public int age;
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.name = "John";
person.age = 20;
}
}
需要注意的是,使用setter方法的方式可以在賦值時對屬性進行一些驗證和處理,而直接訪問屬性的方式無法進行此類操作。所以,最好的習慣是將實體類的屬性設置為私有(private),并提供相應的getter和setter方法來進行賦值和獲取屬性值。