问题
public class Test3 {
public static void main(String[] args) {
Derived04 b = new Derived04();
Base04 a = (Base04)b;
System.out.println(a.i);
System.out.println(a.f());
}
}
class Base04 {
int i=1;
public int f() {return i;}
}
class Derived04 extends Base04 {
int i = 2;
public int f(){return -i;}
}
Both classes include the f() method so when I cast d onto a which method does it go to when I call a.f()? I thinking since a is declared as Base04 type when you do a.i it gives 1 but then why does it use the method from the subclass?
回答1:
The whole point is about implementing and casting. so when you create a Derived04
then you have implemented a Derived04
class, not its parents Base04
so even if you cast it like that it will run the implemented method not the casting method unless there is a different between f()
in both classes. and that's not our case.
回答2:
why does it use the method from the subclass?
You create an object of Derived04
class you just cast it to the type Base04
. It is still Derived04
implementation.
来源:https://stackoverflow.com/questions/61421158/casting-subclass-to-superclass-and-calling-a-function-that-both-classes-have