Reputation: 71
Suppose I have the following classes
class A{
public method(A a) {
System.out.println(3);
}
}
class B extends A{
public void method (A a) {
System.out.println(2);
}
public void method (B b) {
System.out.println(1);
}
}
A obj = new B();
obj.method( (B) obj);
((B) obj).method( (B) obj);
The first method call prints out 2 while the second method call prints out 1. Why don't both method calls print out 1?
Upvotes: 7
Views: 9394
Reputation: 56479
void method (B b)
of B is totally unknown for its parent A.
It's logical, because in obj.method((B) obj);
, the type of obj
is A which in polymorphism rule it can just call void method(A a)
version of class B.
class B extends A {
// This is an overridden method visible to A
public void method(A a) {
System.out.println(2);
}
// This is an overloaded method unknown from A
public void method(B b) {
System.out.println(1);
}
}
You can read this SO answer which explained Override vs. Overload.
Upvotes: 4
Reputation: 839
The first method call is done using object reference of type A, so the corresponding method, which could be overridden, is called.
In the second case first the cast is done to type B, so corresponding method defined in class B ,i.e,
method (B b)
is called.
Upvotes: 1
Reputation: 8432
Because java selects the method to call in compile time. And the compiler only take into account the "left side" of an assignment.
So when you type A obj = new B()
the compiler only "sees" the methods in class A
.
Upvotes: 3