多态
面向对象的三大特性:封装、继承、多态
什么是多态
多态,即同一方法可以根据发送对象的不同而采用多种不同的行为方式
一个对象的实际类型是确定的,但指向对象的引用的类型有很多(父类,有关系的类)
多态的注意事项
1、多态是方法的多态,属性没有多态
2、父类和子类,有联系 类型转换异常!ClassCastException!
3、存在条件:继承关系,方法需要重写,父类引用指向子类对象! Father f1 = new Son();
无法重写,也更不是多态!!!
1、static 方法,属于类,它不属于实例
2、final常量
3、private;
instanceof和类型转换
不是父子类型时,编译不通过
如:
//Object->Person->Student
//Object->Person->Teacher
//Object->String
Person person = new Student();
System.out.println(person instanceof Student);//true
System.out.println(person instanceof Person);//true
System.out.println(person instanceof Object);//true
System.out.println(person instanceof Teacher);//false
System.out.println(person instanceof String);//编译不通过

浙公网安备 33010602011771号