java - 无需转换对象即可访问通用方法

标签 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 .我怎么能管理这个?我应该使用这样的东西吗?如果是这样,我如何从 child 那里继承方法 getPrice()?

public class ProductA extends GeneralProduct

最佳答案

在您的问题中,ProductAProductB 似乎是GeneralProduct 的子类;也就是说,ProductA"is"GeneralProduct,只是更加特化。

如果是这样:使用子类实现的抽象 getPrice 方法定义 GeneralProduct(但请继续阅读¹)。您可能还会取消 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 可以提供的合理实现,则在子类可选。

您甚至可以更进一步,将产品的接口(interface)与实现分开:

public interface Product {
    double getPrice();
}

那么列表就是

List<Product> list = new ArrayList<Product>();

如果您仍然需要 GeneralProduct(如果需要基类),它可以实现该接口(interface)。

public abstract class GeneralProduct implements Product {
    // ...
}

但是如果您根本不需要基类,ProductAProductB 可以自己实现接口(interface)。


但是,继承只是提供功能的一种方式,有时它是正确的方式,有时另一种方法很有用:组合。在这种情况下,GeneralProduct 将“有一个”ProductAProductB,但是 ProductA(和 ProductB ) 与 GeneralProduct 没有"is"关系。

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

public interface Product {
    double getPrice();
}

class ProductA implements Product {
    public double getPrice() {
        // implementation
    }
}

// ...same for ProductB

public class GeneralProduct {
    String label;
    Product product;
    public GeneralProduct(String label, Product product)
    {
        this.label = label;
        this.product = product;
    }

    // You might have something like this, or not
    public double getProductPrice() {
        return this.product.getPrice();
    }
}

// Then using it:
auxList.add("ProductA", new ProcuctA("ProductA"));
auxList.add("ProductB", new ProcuctB("ProductB"));

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

关于java - 无需转换对象即可访问通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40809666/

相关文章:

java - 为什么父类(super class)的实例可以放入子类的数组中?

java - Android必须实现继承的抽象方法

C++继承类显示没有默认构造函数

java - 具有解析推送通知的 Android M 权限

java - 组合字符串数组和迭代器并排序

java - JOptionPane - 显示我自己的 JDialog 子类的对话框

c++ - 基类调用派生类的方法?

python - 使用 __init__ 继承属性

java - 为什么 CTRL+C(用 Awt.Robot 模拟)不能正常工作?

java - AChartEngine getIntent() 显示点值