J. Doe J. Doe -4 years ago 91
Java Question

Java - Overloaded method selection with extended type

I want to understand the logic behind this code:

public class AA
{
private int num;

public void setNum(int num) {
this.num = num;
}

public int getNum() {

return num;
}

public AA(int num) {

this.num = num;
}

public int f(AA val)
{
num = val.num;
return num;
}

}


class BB:

public class BB extends AA
{

public BB(int num) {
super(num);
}
public int f(BB val)
{
setNum(val.getNum()*2);
return getNum();
}

}


main:

public static void main(String[] args) throws Exception
{
AA y1 = new BB(2);
BB y2 = new BB(3);

System.out.println(y1.f(y2));


why the output is 3 and not 6?

EDIT - I know that is not overriding. My question is why it didn't invoke BB's f? I sent BB variable. not AA.

I understand if at compile time it'll choose the A's f but after that it needs to choose B's f.

I tried to add this to AA and it printed 6..

public int f(BB val)
{
System.out.println("Im here");
num =1+ val.getNum()*2;
return num;
}

Answer Source

There is no method overriding,

public int f(AA val)

and

public int f(BB val)

don't have the same signature .

When you call y1.f(y2) (y1 being of type AA and y2 of type BB) :

AA doesn't have a f(BB) method, so the closest one is called which is f(AA), and BB doesn't override this method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download