所以我有一个名为Room
的类,它有以下构造函数:
public class Room
{
public Room(String roomId, String description, double dailyRate)
{
this.roomId = roomId;
this.description = description;
this.dailyRate = dailyRate;
this.status = 'A';
}
}
我有一个名为PremiumRoom
的子类:
public class PremiumRoom extends Room
{
public PremiumRoom(String roomId, String description, double dailyRate, int freeNights, double discountRate, double nextBookingDiscountVoucher)
{
super(roomId, description, dailyRate);
this.freeNights = freeNights;
this.discountRate = discountRate;
this.nextBookingDiscountVoucher = nextBookingDiscountVoucher;
}
}
最后这是我创建数组的地方:
public class TestProgram {
public static final Room[] rooms = new Room[]
{
new Room ("GARDEN0001", "NorthWest Garden View", 45.0),
new Room ("POOL0001", "Poolside Terrace", 90.0),
new Room ("GARDEN0003", "North Garden View", 35.0),
new Room ("GARDEN0005", "West Garden View", 35.0),
new Room ("POOL0002", "Poolside Private", 125.0),
new Room ("GARDEN0004", "South Garden View", 52.0)
};
}
如何从高级房子类创建对象?例如,new Room ("POOL0001", "Poolside Terrace", 90.0)
假设类似于new PremiumRoom ("POOL0001", "Poolside Terrace", 90.0, 1, 150, 50)
,其中包含其他参数。
我该怎么做?
答案 0 :(得分:4)
像这样创建一个PremiumRoom:
Room premium = new PremiumRoom ("POOL0001", "Poolside Terrace", 90.0, 1, 150, 50);
您将能够将其插入阵列...
检索房间时,您必须使用instanceof
确定哪个Room
类,然后转为PremiumRoom