0

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?

Wex
  • 15,539
  • 10
  • 64
  • 107

3 Answers3

5

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

interface myinterface {
    void doSomething();
}

And both B and C must implement myInterface.

michael667
  • 3,241
  • 24
  • 32
1

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.

Tobias
  • 9,170
  • 3
  • 24
  • 30
1

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 A.B and A.C need to implement T.

ControlPower
  • 610
  • 4
  • 7