consider the following code:
public class A{
private int num;
public A(int n){
num = n;
}
public int getNum(){
return num;
}
public boolean f(A a){
return num == a.num * 2;
}
}
public class B extends A {
public B(int n) {
super(n);
}
public boolean f(B b) {
return getNum() == b.getNum();
}
}
public class Main
{
public static void main(String[] args){
A y1 = new B(10);
B y2 = new B(10);
System.out.println("y1.f(y2) is: "+y1.f(y2));
}
}
What I don't understand is why the method f
is running for class A
(and printing false) and not B
, cause in run time y1
is of type B
, and should go down to method f
in class B
?
cause in run time y1 is of type B, and should go down to method f in class B?
No:
B.f()
doesn't override A.f()
because the parameter types are different. It overloads it.If you change B.f()
to accept a parameter of type A
rather than B
, you'll see it get executed. That doesn't depend on the execution-time type of the argument, but on the execution-time type of the target of the call.
The method implementation which is chosen never depends on the execution-time type of an argument.
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