多态
1)继承
2)重写
3)子类对象指向父类引用
关于多态的一个经典案例
public class Test {
public static void main(String[] args) {
student student = new student();
student.eat();
}
}
class person {
public void eat(){
System.out.println("我在吃东西");
sleep();
}
public void sleep(){
System.out.println("我在睡觉");
}
}
class student extends person{
public void sleep(int i){
System.out.println("睡了7小时");
}
}
我之前以为打印输出:
我在吃东西
我在睡觉
实际上会打印输出
我在吃东西
睡了7小时
1)因为方法中默认有2个隐式参数this和super,sleep()实际上是this.sleep(),这段代码中this可不是代表person,而是student
因为new的是student类。(this代表的永远是new的这个类)所以它实际上调用的是student中的sleep方法!
网友评论