超类对象数组。如何将它们作为子类进行管理?

Array of superclass objects. How to manage them as subclass ones?

有这些 类:

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);

}

我正在寻找确保我将 Superclass Furniture 对象作为子类(椅子或 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 尽管铸造或解决方案的设计本身是错误的。

一旦您将其重新分配给公共变量,您的演员表就会丢失。您需要分别处理每种类型:

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
    }
}

现在在您的 Kitchen 中,您只需

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

由于您继承了 Furniture class,因此无需为每个 chairTable

实施 2 methods
private void doSomethingInKitchen (Chair c);
private void doSomethingInKitchen (Table t);

你可以有一个这样的方法

private void doSomethingInKitchen (Furniture f);

并且您可以在 forloop 中摆脱转换并让该方法进行转换。

private void doSomethingInKitchen (Furniture f){

   if(f instanceof Table){
   //code for the table 
   }else{
   //code for the chair
   } 

}