gpt4 book ai didi

java - 父类(super class)对象数组。如何将它们作为子类进行管理?

转载 作者:搜寻专家 更新时间:2023-10-31 20:00:37 25 4
gpt4 key购买 nike

有这些类:

public abstract class Furniture

public class Chair : Furniture

public class Table : Furniture

public class Kitchen
{
ArrayList <Furniture> furnitures;
//other code
public void function ()
{
Furniture furniture = furnitures.get();
doSomethingInKitchen(furniture);
}


private void doSomethingInKitchen (Chair c);
private void doSomethingInKitchen (Table t);

}

我正在寻找可确保将父类(super class)家具对象作为子类(椅子或 table )进行操作的最佳实践。

我尝试了一个简单的转换,但是当我调用该函数时,它与家具对象一起运行,而不是与 table 或椅子一起运行。

我试过的是这样的:

for each Furniture in Array List
if(furniture.get() istance of Table)
{
currentFurniture = (Table) furniture.get();
}

else if (furniture.get() istanceof Chair)
{
currentFurniture = (Chair) furniture.get();
}
doSomethingInKitchen(currentFurniture)

不知道是不是currentFurniture声明为的问题

Furniture currentFurniture;

因此,尽管进行了转换,或者如果解决方案的设计本身有误,它也不会被识别为椅子或 table 。

最佳答案

一旦您将其重新分配给公共(public)变量,您的转换就会丢失。您需要分别处理每种类型:

for (Furniture furniture : furnitures) {
if (furniture instanceof Table) {
doSomethingInKitchen((Table)furniture);
} else if (furniture instanceof Chair) {
doSomethingInKitchen((Chair)furniture);
}
}

但理想情况下,您应该避免完全转换并在子类本身上实现不同的逻辑。例如:

abstract class Furniture {
abstract void doSomethingInKitchen();
}

class Table extends Furniture {
@Override
void doSomethingInKitchen() {
// Table-specific logic
}
}

class Chair extends Furniture {
@Override
void doSomethingInKitchen() {
// Chair-specific logic
}
}

现在在您的厨房中,您只需做

for (Furniture furniture : furnitures) {
furniture.doSomethingInKitchen();
}

关于java - 父类(super class)对象数组。如何将它们作为子类进行管理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37308126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com