如何从另一个子类创建对象?
How do I make an object from another subclass?
所以我有一个名为 Room
的 class,它具有以下构造函数:
public class Room
{
public Room(String roomId, String description, double dailyRate)
{
this.roomId = roomId;
this.description = description;
this.dailyRate = dailyRate;
this.status = 'A';
}
}
我有一个名为 PremiumRoom
的子 class:
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 sub class 创建对象?例如,new Room ("POOL0001", "Poolside Terrace", 90.0)
假设类似于 new PremiumRoom ("POOL0001", "Poolside Terrace", 90.0, 1, 150, 50)
,其中包含附加参数。
我该怎么做?
像这样创建 PremiumRoom:
Room premium = new PremiumRoom ("POOL0001", "Poolside Terrace", 90.0, 1, 150, 50);
您将能够将其插入数组...
检索房间时,您必须使用 instanceof
来确定 Room
中的 class 是哪个,然后转换为 PremiumRoom
所以我有一个名为 Room
的 class,它具有以下构造函数:
public class Room
{
public Room(String roomId, String description, double dailyRate)
{
this.roomId = roomId;
this.description = description;
this.dailyRate = dailyRate;
this.status = 'A';
}
}
我有一个名为 PremiumRoom
的子 class:
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 sub class 创建对象?例如,new Room ("POOL0001", "Poolside Terrace", 90.0)
假设类似于 new PremiumRoom ("POOL0001", "Poolside Terrace", 90.0, 1, 150, 50)
,其中包含附加参数。
我该怎么做?
像这样创建 PremiumRoom:
Room premium = new PremiumRoom ("POOL0001", "Poolside Terrace", 90.0, 1, 150, 50);
您将能够将其插入数组...
检索房间时,您必须使用 instanceof
来确定 Room
中的 class 是哪个,然后转换为 PremiumRoom