Why are contravariant parameter types in Java not allowed for overriding?

谁说胖子不能爱 提交于 2019-11-26 14:22:01

问题


When overriding a method of a superclass, Java allows the return type to be covariant.

Why are contravariant parameter types in contrast not allowed when overriding methods?


回答1:


Because that's called overloading.

In particular, the return type type can be covariant because it is not considered when overloading, and it therefore still matches the superclass or interface's implementation. Parameters are considered when overloading. You very well might have an optimization with Number doSomethingWithNumber(Integer value) compared to Number doSomethingWithNumber(Number value).



来源:https://stackoverflow.com/questions/12439649/why-are-contravariant-parameter-types-in-java-not-allowed-for-overriding

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