Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods selection with Overloading and Overriding

How the JVM chooses which method to execute?

Is it true that the choosing process is divided into 2 parts. First while compiling the JVM looks for a candidate method to execute. It selects the required signature into the declared object class (not the effective one). Once it selected the candidate signature, it starts looking for it in the hierarchy starting from the effective class of the object.
Is this correct?

One more questions:

Here is a classes hierarchy and related methods:

- Class A: +f(short x): int; +f(String x): int;
- Class B extends A: +f(int x): int; +f(String x): int;
- Class C extends A: +f(double x): int; +f(byte x): int;
- Class D extends C: +f(byte x): int; +f(short x): int;
- Class E extends C: +f(char x): int; +f(int x): int;

So:

  • A is superclass for B and C
  • B is subclass of A
  • C is subclass of A
  • C is superclass for D and E
  • D and E are C subclasses

All of these classes have only one method called "f" with mentioned signatures.

I now declare following objects:

A a = new D();
B b = new B();
C c = new E();

1. Why the method call a.f(3) can't be handled and returns an error?

If what i mentioned before is correct this is what should happen:

The JVM looks into Class A for a method with signature f(int x) or any compatible signature (with casting). It finds method f(short x) which should be compatible, right? Then it looks for this very exact signature into Class D, and it finds it executing the D: f(short x). According to my book this isn't correct, why? It can be because short isn't actually a promotion for int and therefore the JVM doesn't consider f(short x) suitable for the call? And therefore won't find any f method compatible and will return an error.

I checked on Google and on any other resource i could find (also on Stackoverflow) but all were very obvious and not enough detailed answers, therefore i thought could be a good thing to ask, i hope it will turn our that the answer will be useful for future students fighting with overloading and overridding :) Thanks in advance.

like image 288
jnardiello Avatar asked Nov 26 '22 09:11

jnardiello


1 Answers

The only two methods that could be called are:

Class A: +f(short x): int; +f(String x): int;

In order for the cast to be valid we need to implicitly cast the integer 3 to either a short or a string.

But you cannot implicitly convert the integer 3 to the smaller size short. And of course it can't be implicitly cast to a string so it can't be handled.

Edit:

Because you put an instance of class D into the A container, the instance a only knows about A methods. You have to cast the instance of a to D in order to call D's methods which then would enable you to implicitly cast the int 3 to a double and call the f(double) method.

like image 171
Grammin Avatar answered Dec 05 '22 07:12

Grammin