要在Java中創(chuàng)建和使用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();
}
}
在這個示例中,我們首先創(chuàng)建了一個House對象,并使用它的displayInfo()方法來顯示房屋信息。然后,我們修改了房屋的房間數量,并再次顯示信息。
希望這可以幫助您創(chuàng)建和使用House對象。如果有任何疑問,請隨時詢問。