【发布时间】:2012-06-17 08:28:03
【问题描述】:
我正在尝试使用泛型编写一个适应不同类型接口的方法。
在这段代码中,我预计 f an g 方法会打印出“BB”而不是“interface A”。为什么会这样?
interface A {
String n="interface A";
}
interface B extends A {
String n = "BB";
}
public class Main {
<T extends A> void f() {
T a = null;
System.out.println(a.n);
}
<T extends A> void g() {
System.out.println(T.n);
}
public static void main(String[] args) {
Main m = new Main();
m.<B>f();
m.<B>g();
}
【问题讨论】:
-
“为什么会这样?” — 什么会发生?您只是告诉我们您预期会发生什么。
-
interfaces 在 Java 中不能有实例变量。它们只能有常量值(即final实例变量),但将常量放入interface被认为是一种不好的做法。 -
这段代码无法编译,是你的问题吗?
-
@Cicada:实际上,代码确实可以编译。
-
接口不应包含非 const 变量
标签: java generics interface polymorphism