[英]How do I make an object from another subclass?
So I have a class called Room
which has the following constructor: 因此,我有一个名为Room
的类,它具有以下构造函数:
public class Room
{
public Room(String roomId, String description, double dailyRate)
{
this.roomId = roomId;
this.description = description;
this.dailyRate = dailyRate;
this.status = 'A';
}
}
I have sub class called PremiumRoom
as such: 我有这样的子类称为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;
}
}
and finally this is where i create the array: 最后这是我创建数组的地方:
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)
};
}
how do i go about creating an object from the premiumroom sub class? 我该如何从premiumroom子类创建对象? For example, new Room ("POOL0001", "Poolside Terrace", 90.0)
suppose to be something like new PremiumRoom ("POOL0001", "Poolside Terrace", 90.0, 1, 150, 50)
, which contains the additional parameters. 例如, new Room ("POOL0001", "Poolside Terrace", 90.0)
假定类似于new PremiumRoom ("POOL0001", "Poolside Terrace", 90.0, 1, 150, 50)
,其中包含附加参数。
How do i do it? 我该怎么做?
Create a PremiumRoom like this: 创建一个这样的PremiumRoom:
Room premium = new PremiumRoom ("POOL0001", "Poolside Terrace", 90.0, 1, 150, 50);
You will be able to insert it to the array... 您将能够将其插入到数组中...
When you retrieve the rooms you must use instanceof
to determine which class of Room
is and then cast to PremiumRoom
检索房间时,必须使用instanceof
来确定Room
类别,然后将其PremiumRoom
为PremiumRoom
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.