package com.itheima.多态; public class Test { //多态好处 public static void main(String[] args) { // //好处1:实现解耦合,右边对象可以随时切换,后续业务随即改变 // People p1=new Teacher(); // p1.run(); // //好处2:可以使用父类类型的变量作为形参,可以接受一切子类对象 // Student student=new Student(); // Teacher teacher=new Teacher(); // go(student); // go(teacher); // //p1.teach();//报错,因为编译看左边,父类没有所以报错了 People p1=new Teacher(); Teacher s1=(Teacher) p1;//强制类型转换 go(p1); //s1.teach();//强制类型转换可能存在问题:编译阶段有继承或者实现关系就可以进行强制转换,但是运行时可能出现类型转换异常 } //好处2:可以使用父类类型的变量作为形参,可以接受一切子类对象 public static void go(People p){ if(p instanceof Teacher){//判断p对象指向老师还是学生 Teacher s2=(Teacher) p; s2.teach(); } else { Student s2=(Student) p; s2.test(); } } } class People{ public String name="父类People的名称"; public void run(){ System.out.println("人可以跑"); } } class Student extends People{ public String name="子类Student的名称"; public void test(){ System.out.println("考试"); } @Override public void run(){ System.out.println("跑的块"); } } class Teacher extends People{ public String name="子类Teacher的名称"; public void teach(){ System.out.println("教书"); } @Override public void run(){ System.out.println("跑的气喘吁吁"); } }
标签:类型转换,p1,JAVA,People,void,多态,public,Student,Teacher From: https://www.cnblogs.com/pengsuoqun123/p/18091407