Reputation: 447
It is easy to put a class into a Object. But when I try to perform methods on it at Line 36:
aClass.getInfo(3);
I get a cannot find symbol
and cannot compile. How could I use a class in a Object? The aim is to use either classA or classB, depending on an int or something else.
package testit;
public class TestIt {
Object aClass;
public interface InFace {
void getInfo(int i);
}
public class ClassA implements InFace {
@Override
public void getInfo(int i) {
System.out.println("ClassA: " + this.getClass() + " " + i);
}
}
public class ClassB implements InFace {
@Override
public void getInfo(int i) {
System.out.println("ClassB: " + this.getClass() + " " + i);
}
}
public void testClass() {
ClassA testA = new ClassA();
ClassB testB = new ClassB();
testA.getInfo(1);
testB.getInfo(2);
int i = 1;
if (i == 1) {
aClass = testA;
} else {
aClass = testB;
}
System.out.println("aClass: " + aClass.getClass());
// aClass.getInfo(3);
}
public static void main(String[] args) {
TestIt test = new TestIt();
test.testClass();
}
}
Upvotes: 0
Views: 45
Reputation: 69480
You should use InFace
to declare your Object aClass;
, because both of your classes implements that interface:
InFace aClass;
Upvotes: 0
Reputation: 62874
Since aClass
will hold only ClassA
or ClassB
, which are both subtypes of InFace
, you can change
Object aClass;
to
InFace aClass;
Then, your variable of type InFace
will support a method, called getInfo(int i)
and your code will compile.
Upvotes: 1