给定任何接口(interface) I
, 可以声明一个变量,该变量包含对类 C
的任何对象的引用实现 I
:
I i = new C();
我想做类似的事情。给定两个接口(interface),我想声明一个变量,该变量包含对实现两个接口(interface)的类的任何对象的引用:
interface Foo { void foo(); }
interface Bar { void bar(); }
class Humpty implements Foo, Bar {
public void foo() { System.out.println("Humpty.foo()"); }
public void bar() { System.out.println("Humpty.bar()"); }
}
class Dumpty implements Foo, Bar {
public void foo() { System.out.println("Dumpty.foo()"); }
public void bar() { System.out.println("Dumpty.bar()"); }
}
public class Program {
public static void main(String[] args) {
// I actually have no idea what the syntax should be.
Random random = new Random();
// Fix: I previously used <? extends Foo, Bar>, thanks Jon Skeet and vijucat
<? extends Foo & Bar> foobar;
if (random.nextBoolean())
foobar = new Humpty();
else
foobar = new Dumpty();
foobar.foo();
foobar.bar();
}
}
我试过上面的代码片段,但是 <? extends Foo, Bar>
导致编译错误。正确的语法应该是什么?我想知道这是否也适用于其他静态类型的 JVM 语言:Scala、Kotlin、Ceylon 等。
最佳答案
如果您不介意抑制臭名昭著的“未经检查的转换”警告,这是一个“解决方案”:
@SuppressWarnings("unchecked")
public class Program {
public static<FooBar extends Foo & Bar> void main(String[] args) {
// Note the explicit cast needed
FooBar foobar = (FooBar) new Humpty();
foobar.foo();
foobar.bar();
// Note the explicit cast needed
foobar = (FooBar) new Dumpty();
foobar.foo();
foobar.bar();
}
}
另请参阅 Jon Skeet 的回答,其中介绍了可以优雅地实现这一点的情况。
老实说,如果没有那么多极端情况,这应该是可能的。 Java 泛型的实现是如此困惑以至于不理解它们可能表明你知道如何明智地分配你的时间,而不是你不是技术领域的专家! :-)
关于java - 引用任何实现两个或多个给定接口(interface)的类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20860880/