在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();
}
}