8
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"

Dragon
  • 193
  • 1
  • 3
  • 7

2 Answers2

5

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.

Community
  • 1
  • 1
aayoubi
  • 11,285
  • 3
  • 22
  • 20
  • The other linked answer is not for the same error as OP, that other answer does talk about type erasure well, but it does not refer to static methods and the key bit of the error which is " but does not hide it" – Jonah Graham Jan 15 '16 at 23:36
2

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.

Community
  • 1
  • 1
André Stannek
  • 7,773
  • 31
  • 52
  • Thank you for the explanation. Currently I am working on a project where we are migrating to Java 7 and huge number of classes has this problem. Apart from this I am also facing issue with methods which has vargs. – Dragon Sep 25 '13 at 07:37
  • You should definitly refactor all those classes as this is a source for errors. – André Stannek Sep 25 '13 at 07:38