多态的注意事项:
package com.cnblogs; //本类用于实现 public class Application { public static void main(String[] args) { //编译看左边,运行看右边 //实例化(学生是一个人) 能调用的方法都是自己重写或者继承父类的方法,子类特有的方法用不了 Persion stu = new Student(); //实例化(老师是一个人) Persion tea = new Teacher(); stu.work();//上学 stu.eat();//干饭 tea.work();//教书 //父子类都有的静态方法,使用的是父类的 stu.sleep();//父类睡觉 } }
package com.cnblogs; /* persion类 */ public class Persion { public void work(){ System.out.println("什么事都干"); } public void eat(){ System.out.println("干饭"); } public static void sleep(){ System.out.println("父类睡觉"); } }
package com.cnblogs; /* student类 */ public class Student extends Persion{ @Override public void work(){ System.out.println("上学"); } public static void sleep(){ System.out.println("子类睡觉"); } public void work2(){ System.out.println("写作业"); } }
package com.cnblogs; public class Teacher extends Persion{ @Override public void work(){ System.out.println("教书"); } }
多态的优势:
多态的使用:
多态下,子类如何调用自己特有的方法呢?
package com.cnblogs; //本类用于实现 public class Application { public static void main(String[] args) { //实例化(学生是一个人) 子类转换为父类,可能会丢失自己的本来的一些方法! Persion obj = new Student(); //强转 stu将这个对象转换为Student类型,我们就可以用Student类型的方法了。 Student stu = (Student)obj; //实例化(老师是一个人) Persion tea = new Teacher(); stu.work();//上学 stu.eat();//干饭 stu.work2();//写作业 //强转 ((Student)obj).work2();//写作业 tea.work();//教书 } }
instanceof :(类型转换)引用类型
package com.cnblogs; //本类用于实现 public class Application { public static void main(String[] args) { //Object > Persion > Student //Object > Persion > Teacher //Object > String Object object = new Student(); //System.out.println(X instanceof Y);能不能编译通过! System.out.println(object instanceof Student);//true System.out.println(object instanceof Persion);//true System.out.println(object instanceof Object);//true System.out.println(object instanceof Teacher);//false System.out.println(object instanceof String);//false System.out.println("=============================================="); Persion persion = new Student(); System.out.println(persion instanceof Student);//true System.out.println(persion instanceof Persion);//true System.out.println(persion instanceof Object);//true System.out.println(persion instanceof Teacher);//false //System.out.println(person instanceof String);//编译报错! System.out.println("=============================================="); Student student = new Student(); System.out.println(student instanceof Student);//true System.out.println(student instanceof Persion);//true System.out.println(student instanceof Object);//true //System.out.println(student instanceof Teacher);//编译错误 //System.out.println(student instanceof String);//编译错误 } }