简体   繁体   中英

Java - Array of Inner Classes inside of Outer Class

Let's say I have:

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

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

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

If I wanted to make an ArrayList that could contain both B and C in such a way that I could call myArray.get(i).doSomething() inside of A, what type would I want to declare my ArrayList?

List<myInterface> . You'll also need an interface for B and C :

interface myinterface {
    void doSomething();
}

And both B and C must implement myInterface .

Your inner classes have to implement an interface; otherwise the compiler can't be sure that all classes have doSomething() methods and won't allow it.

Did you want that define an ArrayList as:

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

No, you could not yet. You also need to declare a parent class named T or interface T which has a method doSomething and your class AB and AC need to implement T.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM