无需转换对象即可访问常用方法

时间:2016-11-25 17:02:05

标签: java inheritance

我有一个类是GeneralProduct,它看起来如下:

public class GeneralProduct()
{
  String label;
  Object obj;
  public GeneralProduct(String label, Object obj)
  {
     this.label = label;
     this.obj = obj;
  }
}

然后我有两个不同的类,ProductAProductB。这两个类都有一个名为getPrice()的常用方法。另一方面,我有一个名为auxList的数组:

ArrayList<GeneralProduct> auxList = new ArrayList<GeneralProduct>();
auxList.add(new GeneralProduct(new ProductA(), "ProductA"));
auxList.add(new GeneralProduct(new ProductB(), "ProductB"));

现在的问题是,我无法从getPrice()中的ProductAProductB类访问auxList。我怎么能管理这个?我应该使用这样的东西吗?如果是这样,我怎样才能从子节点继承getPrice()方法?

public class ProductA extends GeneralProduct

1 个答案:

答案 0 :(得分:5)

在您的问题中,ProductAProductB似乎是GeneralProduct的子类;也就是说,ProductA“是一个”GeneralProduct,只是更专业。

如果是这样:使用抽象GeneralProduct方法定义getPrice(但继续阅读¹),子类实现。你可能也会取消obj,你不需要它:

public abstract class GeneralProduct {
    String label;
    public GeneralProduct(String label)
    {
        this.label = label;
    }

    public abstract double getPrice();
}

class ProductA extends GeneralProduct {
    @Override
    public double getPrice() {
        // implementation
    }
}

// and the same for ProductB

然后:

auxList.add(new ProcuctA("ProductA"));
auxList.add(new ProcuctB("ProductB"));

(但如果您需要它,可以将obj放回去。)

请注意getPrice

>

您甚至可以更进一步,将产品界面与实施分开:

GeneralProduct

然后列表将是

public interface Product {
    double getPrice();
}

如果您仍然需要List<Product> list = new ArrayList<Product>(); (如果需要基类),它可以实现该接口。

GeneralProduct

但是如果您根本不需要基类,public abstract class GeneralProduct implements Product { // ... } ProductA可以自己实现接口。

然而,继承只是提供功能的一种方式,有时它是正确的方式,有时另一种方法很有用:组合。在这种情况下,ProductB会“拥有”GeneralProductProductA,但ProductB(和ProductA)不会有“是”关系与ProductB

这仍然可能涉及一个接口和/或一个抽象类,只是在不同的地方:

GeneralProduct

继承和组合都是强大的工具。