class Person{
private void print(){
System.out.println("Person-->void print(){});
}
public void fun(){
this.print();
}
}
class Student extends Person{
void print(){
Sysetm.out.println("Student-->void print(){}");
}
}
public class OverrideDemo{
public static void main(String[] args){
new Student().fun();
}
}
此处由于继承关系,new Student().fun()调用父类中的fun()方法。不明白的是,虽然子类中没有重写print()方法,而是重新定义了一个方法,但是为什么接下来不调用这个新方法而去调用父类中的print()方法呢
调用fun()方法时,this指代的是父类,然后this.print()调用的就是父类中的print()方法了
如果student重写了print(),就会调用student的print();不然就是person的print()。你可以这样想,student调用fun方法,发现没有这个方法,就向上转型为person类,发现有这个方法就调用fun方法,然后看student有没有重写print方法而决定调用那个print方法。