【发布时间】:2015-05-28 09:49:15
【问题描述】:
所以我有一个名为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)
};
}
如何从 premiumroom 子类创建对象?例如,new Room ("POOL0001", "Poolside Terrace", 90.0) 假设类似于 new PremiumRoom ("POOL0001", "Poolside Terrace", 90.0, 1, 150, 50),其中包含附加参数。
我该怎么做?
【问题讨论】:
-
您已经提出了一个语法正确的解决方案。使用该语法时会收到什么错误消息?
-
您可以将构造函数添加到
PremiumRoom,将 `Room` 实例作为参数,然后将属性复制到自身。如果您需要简单地向数组中添加一个`PremiumRoom`,请将其声明为Room类型并初始化为PremiumRoom。 -
它给了我一个错误,说“PremiumRoom 无法解析为一种类型”
-
您可能没有在 PremiumRoom 类中导入包
-
TestProgram与PremiumRoom是否在不同的包中?
标签: java arrays inheritance constructor subclass