Reputation: 41
I'm trying to solve a problem about method calls in Java that seems really strange, I hope someone can help about it. Here it is the code of the three classes, A is the top class with C inheriting from A and D inheriting from C.
class A {
int f(double x) {
return 1;
}
int f(boolean x) {
return 2;
}
}
class C extends A {
int f(double x) {
return 3;
}
int f(int x) {
return 4;
}
}
class D extends C {
int f(double x) {
return 5;
}
int f(int x) {
return 6;
}
}
public class test {
public static void main(String[] args) {
C b = new D();
A d = new D();
System.out.println(b.f(33));
System.out.println(d.f(33));
}
}
When I call method of object b with an int I get 6, which means that the method f(int x) from class D is called. But when I call the same method on object d I get 5, which means that the method f(double x) from class D is called. Why does it behave like that? Why an integer is considered an integer in one case and a double in the other? It is something related to how I declared the two objects but I can't get it.
Upvotes: 0
Views: 138
Reputation: 2177
The difference is in the type of the objects. b
's reference is of type C
and d
's reference is of type A
. In cases of inheritance, the JVM binds the methods at run-time, meaning that you can only call methods of the reference type, but the overridden method is the one that will run.
When you call the function on d
, the JVM automatically casts to a double
because A
has no corresponding method for an int
argument. Then, the method trickles down to D
because the object is an instance of D
, but it still trickles down as a double
.
Upvotes: 1