Java – why call a method call that takes a parent class as a parameter instead of a method that takes a child class as a parameter?
I have a class named a and a class named B, which extends a
public class Main {
public static void main(String[] args){
B b = new B();
A a = b;
b.f1(a);
}
}
public class A {
.
.
.
public void f1(A a){
if(a instanceof B)
f1((B)a);
else
System.out.println("Nothing");
}
.
.
.
}
public class B extends A {
.
.
.
public void f1(B b){
System.out.println("B::f1(B)");
}
.
.
.
}
I expect F1 in class A to be called first (because a is type A) and actually occurs Then I expect line F1 ((b) a); It is called because a is an instance of B So far, everything has gone as expected However, I think the next method to be called is F1 (b) in class B On the contrary, F1 (a) in class A is called repeatedly, resulting in stack overflow exception Why not call class B F1 (b)? An instance of B is the caller, and the parameter is cast to class B
Solution
F1 (a) is an example method of class A It does not know the subclass method of A Therefore, it cannot call void F1 (b b) of class B Therefore, F1 ((b) a) executes void F1 (a) again
If you want to call F1 (b b), you must call F1 on the instance variable of class B:
public void f1(A a){
if(a instanceof B) {
B b = (B)a;
b.f1(b);
} else {
System.out.println("Nothing");
}
}
