javapolymorphisminner-classesouter-classes

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?


Solution

  • 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.