【问题标题】:How do I make an object from another subclass?如何从另一个子类创建对象?
【发布时间】: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 类中导入包
  • TestProgramPremiumRoom 是否在不同的包中?

标签: java arrays inheritance constructor subclass


【解决方案1】:

像这样创建一个 PremiumRoom:

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

您将能够将其插入到数组中...

当您检索房间时,您必须使用instanceof 来确定@​​987654324@ 是哪个类,然后转换为PremiumRoom

【讨论】:

  • 我之前试过,它给我一个错误说“PremiumRoom 无法解析为一个类型”
  • 我没有导入高级房间课程。 :D 哈哈哈哈哈哈
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多