在Java中,我們可以通過以下步驟來創建對象并賦值:
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 void printInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
Person person = new Person();
person.setName("John");
person.setAge(25);
person.printInfo();
完整的代碼示例:
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("John");
person.setAge(25);
person.printInfo();
}
}