Test03.java 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package course.polymorphism;
  2. /**
  3. * @author WanJl
  4. * @version 1.0
  5. * @title Test03
  6. * @description
  7. * @create 2026/7/24
  8. */
  9. public class Test03 {
  10. public void runPerson(Person p){
  11. p.eat(); //调用 子类对象 重写 Person类的eat()方法
  12. //判断p对象属于哪种类型的对象,根据不同的对象,调用不同子类的特有方法
  13. if (p instanceof Student){
  14. //向下造型 Person p -> Student
  15. Student s=(Student)p;
  16. //这时候就可以调用s特有的方法
  17. s.study();
  18. }else if(p instanceof Teacher){
  19. //向下造型 Person p -> Teacher
  20. Teacher t=(Teacher) p;
  21. //这时候就可以调用t特有的方法
  22. t.play();
  23. }
  24. p.sleep(); //调用 子类对象 重写 Person类的sleep()方法
  25. }
  26. public static void main(String[] args) {
  27. Test03 t=new Test03();
  28. //创建子类的对象
  29. Student s=new Student();
  30. t.runPerson(s);
  31. //直接把上面的两步合成一步
  32. t.runPerson(new Teacher());
  33. }
  34. }