多态
- 即同一个方法可以根据发送对象的不同而采用多种不同的行为方式
- 一个对象的实际类型是确定的,按可以指向对象的引用类型有很多
- 多态存在的条件:
- 有继承关系
- 子类重写父类的方法
- 父类引用指向子类对象
- 注意:多态是方法的多态,属性没有多态
- instanceof
父类
package com.mypackage.oop.demo08;public class Person08 {public void run(){System.out.println("run");}
}/*
多态注意事项:
1.多态是方法的多态,属性没有多态
2.父类和子类之间才能强制转换,否则会有类型转换异常 ClassCastException
3.存在条件:继承关系,父类引用指向子类对象不可重写的方法:1.static 静态方法 属于类 不属于实例2.final 常量3.private 私有*/
子类
package com.mypackage.oop.demo08;public class Student08 extends Person08 {@Overridepublic void run(){System.out.println("son");}public void eat(){System.out.println("eat");}
}
应用
package com.mypackage.oop.demo08;public class Application08 {public static void main(String[] args) {//一个对象的实际类型是确定的new Student08();new Person08();//但对象可以指向的引用类型就不确定了Student08 s1 = new Student08();Person08 s2 = new Student08(); //父类的引用指向子类的类型Object s3 = new Student08();Person08 p1 = new Person08(); //父类的引用指向自己//对象能执行哪些方法,主要看的是等号左边的类型s2.run(); //son//s2.eat(); //会报错//父类虽然可以指向子类,但是不能调用子类独有的方法((Student08)s2).eat(); //进行强制性转换,高转低(父转子)(不能同级之间进行类型转换) //eats1.eat(); //eats1.run(); //sonp1.run(); //run}
}
instanceof
用于判断一个对象是什么类型,判断两个对象是否具有父子关系
package com.mypackage.oop.demo09;public class Application09 {public static void main(String[] args) {//Object > String//Object > Person > Teacher//Object > Person > StudentObject object = new Student();System.out.println(object instanceof Student); //trueSystem.out.println(object instanceof Person); //trueSystem.out.println(object instanceof Object); //trueSystem.out.println(object instanceof Teacher); //falseSystem.out.println(object instanceof String); //falseSystem.out.println("================");Person person = new Student();System.out.println(person instanceof Student); //trueSystem.out.println(person instanceof Person); //trueSystem.out.println(person instanceof Object); //trueSystem.out.println(person instanceof Teacher); //false//System.out.println(person instanceof String); //编译即报错,因为Person和String是无继承关系的,不能进行类型比较System.out.println("================");Student student = new Student();System.out.println(student instanceof Student); //trueSystem.out.println(student instanceof Person); //trueSystem.out.println(student instanceof Object); //true//System.out.println(student instanceof Teacher); //编译即报错,因为Student和Teacher是无继承关系的//System.out.println(person instanceof String); //编译即报错,因为Student和String是无继承关系的System.out.println("================");Object object2 = new Person();System.out.println(object2 instanceof Student); //false 因为person比student大System.out.println(object2 instanceof Person); //trueSystem.out.println(object2 instanceof Object); //trueSystem.out.println(object2 instanceof Teacher); //false 因为person比teacher大System.out.println(object2 instanceof String); //false//只要等号左边的类型没有父子关系,就会编译错误//等号左边的类型有父子关系,右边的类型无父子关系或者父在instanceof前,就会输出false/*类型之间的转换:基本类型的转换 类型的高低父 子 : 强制转换方式与基本类型的强制转换方式一样,前面加个括号写上要转换成的类型父类转为子类没什么影响,因为基本上父类的方法子类都有。但子类转换为父类可能会丢失一些子类本有的方法*///父类引用可以指向子类,子类引用不可以指向父类}
}