public interface Expression {
}
public interface ArithmeticExpression extends Expression {
}
public class StaticMethodDemo {
public static void print(Expression e) {
System.out.println("StaticMethodDemo");
}
public static List<Expression> convert(
Collection<? extends Expression> input) {
return null;
}
}
public class StaticMethodChild extends StaticMethodDemo {
public static void print(ArithmeticExpression e) {
System.out.println("StaticMethodChild");
}
public static List<ArithmeticExpression> convert(
Collection<? extends ArithmeticExpression> input) {
return null;
}
}为什么上面的代码可以在java5中编译,而不能在java7中编译?在Java7中,它给出了“名称冲突:类型为StaticMethodChild的方法convert(集合)具有与类型为StaticMethodDemo的convert(集合)相同的擦除,但没有隐藏它”
发布于 2013-09-25 15:40:22
发布于 2013-09-25 15:32:22
Java不允许覆盖静态方法。请参阅Why doesn't Java allow overriding of static methods?
你唯一能做的就是隐藏一个子类中的静态方法。隐藏意味着它不依赖于被调用的对象的类型,而是依赖于类的类型。请参阅http://docs.oracle.com/javase/tutorial/java/IandI/override.html
现在的问题是,您的子类方法在形式上具有相同的签名,但由于泛型类型,它没有隐藏它。Collection<? extends ArithmeticExpression>既不是Collection<? extends Expression>的相同类型,也不是它的子类型,实际上阻止了正确、明确的隐藏。正如Ayobi所指出的,引入编译器规则是为了确保向后兼容:Method has the same erasure as another method in type
我现在还不能自己尝试,但是当两者都有相同的泛型类型时,这个错误就会消失。虽然我不知道为什么Java 5中没有出现这个错误,但我猜他们在后来的版本中引入了这个编译器规则,因为他们之前没有注意到这一点。
https://stackoverflow.com/questions/18998280
复制相似问题