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

时间:2016-05-18 19:04:35

标签: java inheritance subclass superclass

有这些课程:

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对象作为子类(主席或表)进行操作。

我试过一个简单的演员,但是当我调用它时,它使用Furniture对象操作,而不是使用Table或Chair。

我尝试的是:

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;

因此,尽管进行了铸造或解决方案的设计本身是错误的,但它不会被认为是主席或桌子。

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

由于您继承了Furniture类,因此无需为每个2 methodschair

实施Table
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
   } 

}