Test()
package polymorphism; public class Test { public static void main(String[] args) { People s1 = new Student();//多态 s1.run();//Student run fastly s1.tuy();//只有people有的函数也不报错 just people have // s1.test();报错 //多态存在问题:不能直接调用子类独有方法,可以使用多态下的类型转换实现 //自动类型转换: 父类 变量名=new 子类(); //强制类型转换:子类 变量名 =(子类) 父类变量 Student s2 = (Student) s1;//强制类型转换 s2.test();//此时就可以调用test //强制类型转换注意事项: //1.存在 继承/实现关系 就可以在编译阶段强制类型转换,编译不会报错 //2. 运行时,如果发现对象的真实类型和 强制转换后的类型不同,就会报类型转换异常 的错误 eg:将s1强制转换为Teacher类型时编译不会报错,但是运行时发现不是一个类型就会报错 //因此java建议:使用 instanceof 关键字判断当前对象的真实类型,再进行强转 if (s1 instanceof Teacher) { Teacher s3 = (Teacher) s1; } else { System.out.println("不是同一类型"); } } }
People()
package polymorphism; public class People { public void run(){ System.out.println("people can run"); } public void tuy(){ System.out.println("just people have"); } }
Student()类
package polymorphism; public class Student extends People{ public void run(){ System.out.println("Student run fastly"); } public void test(){ System.out.println("have a test"); } }
Teacher
package polymorphism; public class Teacher extends People{ public void run(){ System.out.println("teacher run slowly"); } public void teach(){ System.out.println("teach Students"); } }