Two methods with the same name in java

拥有回忆 提交于 2019-12-10 18:44:34

问题


I noticed that if I have two methods with the same name, the first one accepts SomeObject and the second one accepts an object extending SomeObject when I call the method with SomeOtherObject, it automatically uses the one that only accepts SomeObject. If I cast SomeOtherObject to SomeObject, the method that accepts SomeObject is used, even if the object is an instanceof SomeOtherObject. This means the method is selected when compiling. Why?


回答1:


That's how method overload resolution in Java works: the method is selected at compile time.

For all of the ugly details, see the Java Language Specification §15.12.




回答2:


This means the method is selected when compiling.

Yes you are correct. That is what it means.

Why?

I can think of four reasons why they designed Java this way:

  • This is consistent with the way that other statically typed OO languages that support overloading work. It is what people who come / came from the C++ world expect. (This was particularly important in the early days of Java ... though not so much now.). It is worth noting that C# handles overloading the same way.

  • It is efficient. Resolving method overloads at runtime (based on actual argument types) would make overloaded method calls expensive.

  • It gives more predictable (and therefore more easy to understand) behaviour.

  • It avoids the Brittle Base Class problem, where adding adding a new overloaded method in a base class causes unexpected problems in existing derived classes.

References:

  • http://blogs.msdn.com/b/ericlippert/archive/2004/01/07/virtual-methods-and-brittle-base-classes.aspx



回答3:


Yes the function to be executed is decided at compile time! So JVM has no idea of the actual type of the Object at compile time. It only knows the type of the reference that points to the object given as argument to the function.

For more details you can look into Choosing the Most Specific Method in Java Specification.



来源:https://stackoverflow.com/questions/18265638/two-methods-with-the-same-name-in-java

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