要在Java中创建和使用House对象,您需要按照以下步骤进行:
public class House {
private String address;
private int numOfRooms;
public House(String address, int numOfRooms) {
this.address = address;
this.numOfRooms = numOfRooms;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getNumOfRooms() {
return numOfRooms;
}
public void setNumOfRooms(int numOfRooms) {
this.numOfRooms = numOfRooms;
}
public void displayInfo() {
System.out.println("House address: " + address);
System.out.println("Number of rooms: " + numOfRooms);
}
}
public class Main {
public static void main(String[] args) {
House myHouse = new House("123 Main St", 3);
System.out.println("My house:");
myHouse.displayInfo();
// 修改房屋信息
myHouse.setNumOfRooms(4);
myHouse.displayInfo();
}
}
在这个示例中,我们首先创建了一个House对象,并使用它的displayInfo()方法来显示房屋信息。然后,我们修改了房屋的房间数量,并再次显示信息。
希望这可以帮助您创建和使用House对象。如果有任何疑问,请随时询问。