Casting subclass to superclass and calling a function that both classes have

谁说胖子不能爱 提交于 2021-02-08 11:10:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!