Overriding a method with a generic return type fails after adding a parameter

自闭症网瘾萝莉.ら 提交于 2019-11-30 06:37:22

According to the compiler output, the method signatures are different in both examples (compile the code with -Xlint:unchecked option to confirm it):

<X>getSupplier() in A (m2)
                                 1st snippet
getSupplier()    in B (m1)


<X>getSuppliers(Collection<String> strings) in A (m2)
                                                           2nd snippet
getSuppliers(Collection<String> strings)    in B (m1)

According to the JLS specification, the signature of a method m1 is a subsignature of the signature of a method m2 if either:

  • m2 has the same signature as m1, or

  • the signature of m1 is the same as the erasure of the signature of m2.

The first statement is out of the game - method signatures are different. But what about the second statement and erasure?

Valid Override

B.getSupplier() (m1) is a subsignature of A.<X>getSupplier() (m2), because:

  • the signature of m1 is the same as the erasure of the signature of m2

<X>getSupplier() after erasure is equal to getSupplier().

Invalid Override

B.getSuppliers(...) (m1) is not a subsignature of A.<X>getSuppliers(...) (m2), because:

  • the signature of m1 is not the same as the erasure of the signature of m2

The signature of m1:

getSuppliers(Collection<String> strings);

Erasure of the signature of m2:

getSuppliers(Collection strings);

Changing m1 argument from Collection<String> to the raw Collection eliminates an error, in this case m1 becomes a subsignature of m2.

Conclusion

1st  code snippet (valid override): the method signatures in the parent and child classes are different initially. But, after applying the erasure to the parent method the signatures becomes the same.

2nd code snippet (invalid override): the method signatures are different initially and remains different after applying the erasure to the parent method.

The moment you added the parameter it ceased to be an override and became an overload.

Generics have nothing to do with it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!