public class Question {
public static void main(String[] args) {
MyInterface child = new Child();
//接口多态参数 和 继承 同时出现时的 两种动态绑定现象
//1、正常的动态绑定现象
// child.toSay();//编译报错:Cannot resolve method 'toSay' in 'MyInterface',可以理解
System.out.println(((Dad) child).toSay());//输出"toSay Child...",可以理解
child.toString();//不报错,无法理解???
//2、二次动态绑定现象
System.out.println(child.toString());//输出"toSay Child...",无法理解???
}
}
interface MyInterface {
}
class Grandpa {
public String toSay() {
return "toSay Grandpa...";
}
}
class Dad extends Grandpa implements MyInterface {
public String toString() {
return toSay();
}
public String toSay() {
return "toSay Dad...";
}
}
class Child extends Dad {
public String toSay() {
return "toSay Child...";
}
}
这两次动态绑定,绑定的东西好像不一样。
第一次(调用toString)是绑定child,但为什么child可以调用MyInterface接口中没有的toString方法?(问题一)
toString方法并没有在接口中定义,属于实现类的私有方法,按说是不能被向上转型后的child调用的。
第二次(在toString内部调用toSay)不知道绑定了啥,但肯定不是child了吧。
因为toSay是实现类的私有方法,且child.toSay();会编译报错。
那第二次绑定的是啥呢?或者说第二次的动态绑定规则是啥呢?(问题二)
虽然子类重写,调用的是父类的tostring,但是重写了,say.记住一个原则,只要子类重新的方法都以子类为准,望采纳!谢谢