public class People {
private String name = "张三";
public void sleep(){
System.out.println("People : sleep");
}
public void eat(){
this.sleep();//Student : sleep
System.out.println(this.name);//People
System.out.println(this.getName());//Student
System.out.println("吃饭");
}
public String getName() {
return name;
}
}
public class Student extends People{
private String name = "李四";
@Override
public void sleep(){
System.out.println("Student : sleep");
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
我想问的是 现在我写一个测试类Test使父类People引用指向了子类Student对象
调用eat方法
父类eat方法中
public void eat(){
this.sleep();//Student : sleep
System.out.println(this.name);//People
System.out.println(this.getName());//Student
System.out.println("吃饭");
}
第一行输出Student : sleep 很好理解 因为方法有多态特性,子类重写了sleep方法
所以会调用子类的。
第二行this.name (这个this本身是 Student对象 因为属性没有多态特性 所以就用父类的)
但是 我们通过this调用 (应该调用的对象自己的 因为这里的this是Student对象,应该并不会知道 引用是People类型,难道就是因为 我在父类中 所以我的this就是父类类型吗)
第三行 问题和第二行一样 输出的子类的 假如this在哪就是 哪个类型。那么就能解决我的问题。
但是 我并不知道 this是不是在哪个类中 就是哪个类型。这个只是我自己猜的。希望高手解惑。我的问题也就是这个
this是指当前对象,也就是你实例化的这个类,这个类是子类的对象,但却是父类的类型
this就是当前类的指针。多态是通过编译的时候动态创建一个虚拟表格里面把虚函数还有基类以及子类的地址增加进去,通过查询虚拟表格达到函数准确的调用。