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;
}
}
Above code compiles in java 5 but not in java 7 why? In java 7 it gives "Name clash: The method convert(Collection) of type StaticMethodChild has the same erasure as convert(Collection) of type StaticMethodDemo but does not hide it"
Besides stonedsquirrel's answer, even if the methods were not static, you would get the same error.
This is because of Type Erasure, you would be trying to override convert with an incompatible type.
Check the following answer for a nice explanation.
Java doesn't allow overriding of static methods. See Why doesn't Java allow overriding of static methods?
The only thing you can do is hide a static method in a subclass. Hiding means it is not dependent on what type of object it is called, but on what type of class. See http://docs.oracle.com/javase/tutorial/java/IandI/override.html
Now the problem is, your subclass method has formally the same signature but because of the generic types it is not hiding it. Collection<? extends ArithmeticExpression>
is neither the same nor a subtype of Collection<? extends Expression>
practically preventing correct, unambigous hiding. As Ayobi pointed out, the compiler rule was introduced to ensure backwards compatability: Method has the same erasure as another method in type
Can't try it for myself right now but the error should disapear whenn both have the same generic types. Although I have no idea why the error doesn't occur in Java 5. I guess they introduced that compiler rule in a later version because they didn't notice it before.