Two methods with the same name in java

extends, java, methods

Solution

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.

Problem

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?

Original source