The name Clash compiles a compilation error in java 7, but works fine in java 5

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; } } 

The above code compiles in java 5, but not in java 7 why? In java 7 it gives "Collision name: the convert (Collection) method of type StaticMethodChild has the same erase as the conversion (Collection) of type StaticMethodDemo, but does not hide it"

+8
java compiler-errors
source share
2 answers

Besides stonedsquirrel's answer, even if the methods were not static, you will get the same error.

This is due to Type Erasure, you are trying to override a conversion with an incompatible type.

Mark the answer for a pleasant explanation.

+4
source share

Java does not allow overriding static methods. See Why Java does not allow overriding static methods?

The only thing you can do is hide the static method in a subclass. Hiding means that it does not depend 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 that your subclass method is formally the same signature, but because of the generic types, it does not hide it. Collection<? extends ArithmeticExpression> Collection<? extends ArithmeticExpression> is neither the same nor a subtype of Collection<? extends Expression> Collection<? extends Expression> , which virtually prevents correct, unambiguous hiding. As Iobi noted, a compiler rule was introduced to ensure backward compatibility: The method has the same erasure as another method in the type

I can’t try this for myself right now, but the error should disappear if both have the same common types. Although I have no idea why the error does not occur in Java 5. I assume that they introduced this compiler rule in a later version because they had not noticed it before.

+2
source share

All Articles