public interface Foo {
}
public class ExtendedFoo implements Foo {
public void myMethod() {
System.out.println(1);
}
}
public class AnotherExtendedFoo implements Foo {
@Override
public String toString() {
return "hello world"
}
}
public class UnknownImplementedFoo {
public final Foo foo; // can be either ExtendedFoo OR AnotherExtendedFoo
public UnknownImplementedFoo(ExtendedFoo f) {
this.foo = f;
}
public UnknownImplementedFoo(AnotherExtendedFoo f) {
this.foo = f;
}
}
...
public void myTest() {
ExtendedFoo f1 = new ExtendedFoo();
AnotherExtendedFoo f2 = new AnotherExtendedFoo();
UnknownImplementedFoo ifoo1 = new UnknownImplementedFoo(f1);
System.out.println(ifoo1.foo.myMethod()); // can't access myMethod!
System.out.println(ifoo1.type); // prints ExtendedFoo@21599f38
// it knows which type of Foo it is
// so why can't it call its custom methods?
UnknownImplementedFoo ifoo2 = new UnknownImplementedFoo(f2);
System.out.println(ifoo2); // prints hello world
}
...
The problem is shown at the end (myTest method), where I cannot access attributes/methods of the classes that extend the inteface.
Is there any workaround?
That is, I want UnknownImplementedFoo
to take ANY class that implements Foo
(ie. not just these 2), while still being able to access the public attributes/methods.