Dries Coppens Dries Coppens - 3 months ago 11
Java Question

Method overloading exercise

I got this exercise on my exam but I can't figure out 1 solution. So I was given this:

public class X {
public int f(A a, int n) {
n = n + 1;
return 1;
}

public int h(B b, int n) {
try {
n = n + 3;
return f(b,n);
} catch(Exception e) {
return n * 4;
}
}
}

public class Y extends X {
public int f(A b, int n) {
return n + b.i();
}

public int f(B b, int n) {
return 3*n - b.i();
}
}

public class Z extends Y {
public int f(B b, int n) {
return f((A)b,n) + super.f(b,n);
}
}

public class A {
public int i() {
return 7;
}
}

public class B extends A {
public int i() {
return super.i() + 6;
}
}

static class E extends RuntimeException {
}


And I needed to figure out:

new Z().h(new B(), 3)


The solution is 19 but I don't understand why the f method of class Y is used instead of the f method of class Z.

Answer

The signature of the method being called is determined at compilation time, not runtime. The call to f is in X's h:

return f(b,n);

If you look at X, the only f it can call is its f(A, int). It doesn't have access to an f(B, int). So it's compiled with a call to f(A, int). Y overrides f(A, int) and Z does not, and so anything that's a Y instance (including Z instances) will use Y's version of f(A, int). So Y's f(A, int) is used.

Comments