0

假设我有:

public class A {
  public A() {
    ...
  }
  ...

  public class B {
    public B() {
      ...
    }
    public void doSomething() {
      ...
    }
    ...
  }

  public class C {
    public C() {
      ...
    }
    public void doSomething() {
      ...
    }
    ...
  }
}

如果我想创建一个可以同时包含 B 和 C 的 ArrayList,并且我可以myArray.get(i).doSomething()在 A 内部调用,那么我想声明我的 ArrayList 的类型是什么?

4

3 回答 3

5

List<myInterface>. 您还需要一个用于Band的接口C

interface myinterface {
    void doSomething();
}

两者兼而有之。B_Cimplement myInterface

于 2011-10-06T08:30:25.877 回答
1

你的内部类必须实现一个接口;否则编译器不能确定所有的类都有 doSomething() 方法并且不会允许它。

于 2011-10-06T08:31:34.643 回答
1

您是否希望将 ArrayList 定义为:

ArrayList<T> al = new ArrayList<T>();
...
al.get(0).doSomething();

不,你还不能。您还需要声明一个名为 T 或接口 T 的父类,它有一个方法 doSomething 并且您的类 AB 和 AC 需要实现 T。

于 2011-10-06T08:33:41.443 回答