2015-05-28 50 views
0

所以我有一个叫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),其中包含其他参数。

我该怎么做?

+0

您已经提出了正确语法的解决方案。使用该语法时会得到什么错误消息? – dhke

+0

您可以将一个构造函数添加到以'Room'实例作为参数的'PremiumRoom'中,然后将这些属性复制到它自己。如果您只需要将“PremiumRoom”添加到数组中,请将其声明为“Room”类型并初始化为“PremiumRoom”。 – Mena

+0

它给了我一个错误,说“PremiumRoom不能解析为类型” – SadJavaBoi

回答

4

这样创建PremiumRoom:

Room premium = new PremiumRoom ("POOL0001", "Poolside Terrace", 90.0, 1, 150, 50); 

您可以将其插入到数组...

当您检索的房间,你必须使用instanceof确定哪些Room类然后投射到PremiumRoom

+0

我之前试过,它给了我一个错误,说“PremiumRoom不能解析为类型” – SadJavaBoi

+0

我没有导入premiumroom类。 :D haha​​hahahaha – SadJavaBoi

+1

感谢您的帮助! :) – SadJavaBoi

相关问题