0

The title can be a bit confusing, let me explain with an example.
Suppose that I have two classes:

class Parent {} 

class Child extends Parent {} 

Then somewhere else I define a method that has a single parameter of type Parent, like this:

public void doSomething(Parent parameter) {...}

Because of polymorphism I can pass to the method above also an object of type Child because it extends Parent.

Now let's do an overload

public void doSomething(Parent parameter) {...}

public void doSomething(Child parameter) {...}

and then in some other part of the code call doSomething passing a parameter of type Child

Child myElement = new Child();
doSomething(myElement);

In this case both the overloaded method are valid because the element of type Child can be passed to both.
Which one will be called?

I wrote a test and it seems that the second one (the one that takes the parameter of type Child in input) is executed, and it make also sense to me, but I would like to know if it is a well defined behavior or can vary basing on for example the jvm implementation or the order in which the two methods are declared or just randomly etc.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
user2572526
  • 1,219
  • 2
  • 17
  • 35
  • Everything in Java is defined (and if it isn't, that is probably a bug). If you want the nitty-gritty details look at [JLS 8.4.9 Overloading](https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.4.9) and [JLS 15.12 Method Invocation Expressions](https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.12). – Mark Rotteveel Dec 19 '18 at 16:15

1 Answers1

1

Generally speaking, the method with the most specific parameters will be called. In your example, the method that takes a Child is more specific than the method that takes a Parent so it's the former that is called.

The actual rules are somewhat complex but are well defined and part of the language specification. A valid compiler or JVM must follow those rules.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • 1
    OK but pay attention to this: in case of `Parent myElement = new Child()`, the call `doSomething(myElement)` will invoke the first one. – Robert Kock Dec 19 '18 at 16:05
  • "the actual rules are somewhat complex" but most definitely not dependent upon the implementation or the declaration order. – Andy Turner Dec 19 '18 at 16:06