简体   繁体   中英

Two methods with the same name in java

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?

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.

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM