@(跃迁之路)专栏
叨叨两句
- 技术的精进不能只是简单的刷题,而应该是不断的“刻意”练习
- 该系列改版后正式纳入【跃迁之路】专栏,持续更新
1
package Wangyi;class Base{ public void method() { System.out.println("Base"); } }class Son extends Base{ public void method() { System.out.println("Son"); } public void methodB() { System.out.println("SonB"); }}public class Test01{ public static void main(String[] args) { Base base = new Son(); base.method(); base.methodB(); }}
问这个程序的输出结果。
正确答案: D 你的答案: B (错误)
A Base SonBB Son SonBC Base Son SonBD 编译不通过Base base=new Son(); 是多态的表示形式。父类对象调用了子类创建了Son对象。base调用的method()方法就是调用了子类重写的method()方法。而此时base还是属于Base对象,base调用methodB()时Base对象里没有这个方法,所以编译不通过。要想调用的话需要先通过SON son=(SON)base;强制转换,然后用son.methodB()调用就可以了。