Given the following Java code:
class mainul {
public static void main(String[] args) {
/*block 1*/
B b1 = new B();
A a1 = b1;
a1.m1(b1);
/*block 2*/
B b2 = new B();
B a2 = b2;
b2.m1(a2);
}
}
class A {
public static void p(Object o) {
System.out.println(o.toString());
}
public void m1(A a) {
p("m1(A) in A");
}
}
class B extends A {
public void m1(B b) {
p("m1(B) in B");
}
}
Can someone shed some light to why the output of this program is
m1(A) in A
m1(B) in B
One would expect the output of block 1 to be "m1(B) in B" due to the fact the dynamic type of a1 is B. I noticed that the function signatures in A and B for m1 do not match (one expects an object of type A and the other of B as its argument), and the method in A seems to get priority, but I can't really link this to my output as it doesn't seem to be consistent with the output of block 2.
As you noticed, B.m1(B) does not override A.m1(A), as they take different arguments (try adding the @Override annotation and you'll see the compiler complain). So so it can never be called via a reference to an A.
It can, however, be called via a reference to a B.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With