| 123456789101112131415161718192021222324252627282930313233343536373839404142 |
- package course.polymorphism;
- /**
- * @author WanJl
- * @version 1.0
- * @title Test03
- * @description
- * @create 2026/7/24
- */
- public class Test03 {
- public void runPerson(Person p){
- p.eat(); //调用 子类对象 重写 Person类的eat()方法
- //判断p对象属于哪种类型的对象,根据不同的对象,调用不同子类的特有方法
- if (p instanceof Student){
- //向下造型 Person p -> Student
- Student s=(Student)p;
- //这时候就可以调用s特有的方法
- s.study();
- }else if(p instanceof Teacher){
- //向下造型 Person p -> Teacher
- Teacher t=(Teacher) p;
- //这时候就可以调用t特有的方法
- t.play();
- }
- p.sleep(); //调用 子类对象 重写 Person类的sleep()方法
- }
- public static void main(String[] args) {
- Test03 t=new Test03();
- //创建子类的对象
- Student s=new Student();
- t.runPerson(s);
- //直接把上面的两步合成一步
- t.runPerson(new Teacher());
- }
- }
|