Legal calls and definition of overloaded functions in Java

I self-medicate in the summer, and I ran into this problem, which I am not sure about, and I was wondering if anyone could help. I am not sure about the last issue, but I have included my previous answers if someone wants to check them. This is not homework for any class, I just want to make sure that I understand what I am doing before moving on.

I consider the following definitions:

1. void m (Object o, long x, long y) 2. void m (String s, int x, long y) 3. void m (Object o, int x, long y) 4. void m (String s, long x, int y) 

which these ads:

 Object o; String v; int a; long b; 

and I consider these challenges:

 m(v,a,b); Calls 2, because it is the most specific. m(v,a,a); Not legal, because 2 and 4 could both be called (not specific enough). m(v,b,a); Calls 4, because it is the most specific. m(v,b,b); Calls 1, because it is the only one that will fit (long cannot shorten to int). m(o,b,b); Calls 1, similar reasoning as above answer. m(o,a,a); Unsure. I'm not sure of the precedence. 

Thanks in advance!

+6
source share
3 answers

This is a simple case of "the most concrete." Option 3 is selected for the same reason that your second call is illegal. m(v,a,a) cannot choose between m(String,long,int) and m(String,int,long) , because they are equally specific. Each of them requires one extended conversion of one of the arguments. m(o,a,a) , on the other hand, can choose between m(Object,long,long) and m(Object,int,long) . One of them requires two expanding transformations. The other requires only one, which makes it the most specific.

+2
source

The latter will call 3. Since the first argument is Object, it can only select one of the methods with Object as the first argument, so that 1 or 3 remains as an option. The third argument int fits into long , which is legal in both cases. The second argument can be set exactly to 3, while it must be extended to fit in 1. The compiler prefers exact matching by extension.

Your previous answers are correct.

+2
source

m (V, b, b); Calls 1 because it is the only one that will match (long cannot shorten to int).

Another reason for this call to 1 is related to polymorphism and a hierarchy based on a single Java hierarchy. A string (or any object) is a descendant of the Object class. Any method that takes an object as an argument can take a string - the essence of polymorphism.

0
source

Source: https://habr.com/ru/post/945955/


All Articles