Question

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?

Was it helpful?

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.

OTHER TIPS

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

interface myinterface {
    void doSomething();
}

And both B and C must implement myInterface.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top