问题
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