【发布时间】:2016-10-09 14:09:37
【问题描述】:
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
}
...
问题显示在最后(myTest 方法),我无法访问扩展接口的类的属性/方法。
有什么解决方法吗?
也就是说,我希望 UnknownImplementedFoo 采用任何实现 Foo 的类(即不仅仅是这两个),同时仍然能够访问公共属性/方法。
【问题讨论】:
-
请注意,您的最后一条语句没有输出“hello world”
标签: java