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