开发者社区 问答 正文

将抽象对象转换为子类对象

我正在尝试编译:

Property flat = new Flat(1, "Street", "City", "BDK 8DN", 2, 1);

属性是一个抽象类,而Flat是一个子类。

public class Flat extends Property

Flat包含Property中的所有抽象方法。

我在Property上有警告,在新Flat()上有错误

无法从公寓转换为物业

对泛型类型Property的引用应参数化

编辑

额外的代码:

属性

public abstract class Property {
    private int number;
    private String street;
    private String city;
    private String postCode;
    private int numberOfRooms;
    protected Map<Room, ITenant> rooms = new HashMap<Room, ITenant>();

    public Property(int number, String street, String city, String postCode, int numberOfRooms) {
        super();
        this.number = number;
        this.street = street;
        this.city = city;
        this.postCode = postCode;
        this.numberOfRooms = numberOfRooms;
    }

    public abstract String displayOccupiedProperty();

    public abstract boolean isAvailable();

    public abstract void occupyRoom(Room room, ITenant tenant);
}

平面

public class Flat extends Property {

    private int floor;

    public Flat(int number, String street, String city, String postCode, int numberOfRooms, int floor) {
        super(number, street, city, postCode, numberOfRooms);
        this.floor = floor;
    }

  • Property中的四种覆盖方法

public class House extends Property {

    public House(int number, String street, String city, String postCode, int numberOfRooms) {
        super(number, street, city, postCode, numberOfRooms);
    }

  • Property中的四种覆盖方法

测试文件

public class PropertyTest {

    @Test
    public void testFlat() {
        Property flat = new Flat(1, "Street", "City", "BDK 8DN", 2, 1);
    }

展开
收起
垚tutu 2019-12-12 09:44:43 520 分享 版权
阿里云 AI 助理回答

从你提供的代码片段来看,问题可能出在泛型警告上。你的Property类中定义了一个rooms字段,它是一个未指定类型的HashMap。这通常会导致编译器发出警告,建议为泛型类型参数化以确保类型安全。

要解决这个问题,你需要明确地指定HashMap的键和值类型。根据你的描述,没有直接提供RoomITenant的具体实现,但假设rooms是用于存储房间及其租户的,你可以将HashMap的类型设置为<Integer, ITenant>(这里我假设用房间号作为键,租户作为值,具体类型请根据实际情况调整)。修改后的Property类部分如下:

public abstract class Property {
    // ... 其他属性 ...
    protected Map<Integer, ITenant> rooms = new HashMap<>();

    // ... 构造函数和其他方法 ...
}

同时,请确保所有使用到rooms的地方都与这个类型设定保持一致,并且已经定义了ITenant接口或类。

至于错误“无法从公寓转换为物业”,看起来像是一个类型转换的问题,但从你给出的代码片段中并没有直接体现这一点。如果在其他地方有进行类型转换操作,请检查是否有必要,因为Flat已经是Property的子类,正常情况下不需要显式转换。

如果问题仍然存在或者上述修改不完全适用,请提供更详细的错误信息或相关代码上下文,以便进行更准确的诊断。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答地址: