有大佬懂,这里为啥father s = new son();了s还能调用son类的方法吗?
father里面也有print方法啊,肯定能调用。
题主是想说为啥输出的是son方法的内容吧,这就是重写的基本特性了,给你推荐篇博文看看 https://blog.csdn.net/qq_42066648/article/details/114288588
public class Test {
public static void main(String[] args) {
Father f = new Son();
f.test1();//子类重写,调用子类方法
f.test2();//子类没有重写,调用父类方法
//f.test3();//子类特有方法,无法被调用
}
}
class Son extends Father{
//继承的父类方法
@Override
void test1() {
System.out.println("son-----test1");
}
//子类特有方法
void test3(){
System.out.println("son-----test3");
}
}
class Father {
void test1() {
System.out.println("father-----test1");
}
void test2(){
System.out.println("father-----test2");
}
}
总的来说,父类指向子类对象。
只能调用父类自己的方法。
子类重写,则调用子类方法。没重写则调用父类自己的。
子类特有的方法,父类无法调用。
首先,建议类名首字母大写。
其次,您的代码中,son类重写了father类的print方法,对于
father s = new son();
s.print(xxx);
编译时,s.print方法调用的invokevirtual指令的参数指向的是father的print方法(即:father.print:(I)V),也就是你截图打箭头这里,编译器提示的其实是father的print方法。
但是在执行的时候,java方法调用是动态单分派,编译期虽然确定的了静态类型为father,需要调用方法签名是father的print方法,但是方法的接收者是参数s的实际类型,最终调用的会是son的print方法。
总结来说就是,你这个代码编译成字节码之后,方法指向的是father.print(符号引用),运行的时候调用的是son.print,这个涉及到执行引擎动态分派的流程,更详细的内容可以参考:
https://blog.csdn.net/huangzhilin2015/article/details/114437682