gpt4 book ai didi

java - 在将扩展类初始化为接口(interface)时调用扩展类的方法

转载 作者:行者123 更新时间:2023-11-29 07:32:37 27 4
gpt4 key购买 nike

<分区>

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 方法),我无法访问扩展接口(interface)的类的属性/方法。

有解决办法吗?

也就是说,我希望 UnknownImplementedFoo 采用任何实现了 Foo 的类(即不仅仅是这两个),同时仍然能够访问公共(public)属性/方法.

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com