多态
多态存在的必要条件
-
必须要有继承关系
-
子类必须要重写父类的方法
-
父类的引用指向子类的对象
人类(父类)
/**
* 人类(父类)
*/
public class Person {
public void eat(){
System.out.println("人类的吃饭方法");
}
}
学术类(子类)
/**
* 学生类(子类)
*/
public class Student extends Person { //继承父类
测试类
/**
* 测试类
*/
public class Application {
public static void main(String[] args) {
Student student = new Student();
Person person = new Student(); //父类的引用指向了子类的对象
student.eat(); //因为自身就是student对象,所有输出的就是重写后的方法 “学生的吃饭方法”
person.eat(); //因为student重写了person的方法,所有这里输出的是 “学生的吃饭方法”
}
}
注意

浙公网安备 33010602011771号