- Java三大特性,封装+继承==>多态
- 对象的多态是多态的核心和重点。
- 重载:方法名相同而参数列表不同的
- 覆盖:方法名与参数列表均相同
- 动态绑定:
- 表现形式:Person p = new Student()
- 访问属性时访问的时引用变量类型【父类】的属性,执行方法时执行的是实际对象类型【子类】的方法
- 代码示例
//父类
public class Father {
private String name = "father";
public void eat(){
System.out.println("father eat!");
}
public void drink(){
System.out.println("father drink!");
}
public void fatherMethod(){
System.out.println("father method!");
}
}
/**
*演示java多态:
* 1.重载
* 2.覆盖
* 3.子类能调用同名父类方法
* 4.子类能调用自身不存在的父类方法
* 5.动态绑定
*/
public class children extends Father{
private String name = "children";
//重载
public void eat(String food){
System.out.println("children eat a "+food);
}
//覆盖
public void drink(){
System.out.println("children drink!");
}
@Test
public void childrenTest() {
//子类对象
children c1 = new children();
//父类对象
Father f = new Father();
//动态绑定:父类声明指向子类实例
Father c2 = new children();
//重载
c1.eat("tomato");
//覆盖
c1.drink();
f.drink();
//子类能够调用父类方法
super.drink();
//子类能够自动调用父类方法
c1.fatherMethod();
//动态绑定
//编译时c2的是Father类型的,其drink()方法自然也是父类的方法(静态绑定)
//运行时在堆内的c2是children类型,其drink()方法自然也是重写的方法(动态绑定)
//父类定义的对象可以接受所有的子类对象
//对象执行方法时是由实际对象决定的(此例的children)
//对象访问属性时室友引用变量的类型决定的(此例的father),因为编译程序在分析程序时是基于类型来决定访问哪个属性变量
c2.drink();//children eat
}
}
运行结果: