Day10_多态
多态
动态编译:(类型)只有在执行是才能确定
即同一个方法可以根据发送对象的不同而采取多种不同的行为方式
一个对象的实际类型是确定的,但可以指向对象的引用类型有很多(父类或有关系的类)
通过多态可以让我们的程序可拓展性变强
(Java的实例方法调用是基于运行时的实际类型的动态调用,而非变量的声明类型。这个非常重要的特性在面向对象编程中称之为多态。它的英文拼写非常复杂:Polymorphic)
// 继承关系
// >Obj>Person>Teacher
// >Obj>Person>Student
// >Obj>String
Object object = new Student();
System.out.println(object instanceof Student);
System.out.println(object instanceof Person);
System.out.println(object instanceof Object);
System.out.println(object instanceof String);
System.out.println("====================");
Person person = new Student();
System.out.println(person instanceof Student);
System.out.println(person instanceof Person);
System.out.println(person instanceof Object);
System.out.println(person instanceof Teacher);
//两边没有关系编译就会报错,编译看左,运行看右
// System.out.println(person instanceof String);
Student student = new Student();
System.out.println(student instanceof Student);
//两边没有关系编译就会报错,编译看左,运行看右
// System.out.println(student instanceof Teacher);
System.out.println(student instanceof Person);
// System.out.println(student instanceof String);
多态的注意事项(重要)
1.多态是方法的多态,属性没有多态
2.父类和子类,有联系的 类型转换异常ClassCastException
3.存在的条件,继承关系,方法的重写。父类引用指向子类对象
Father f1 = new Son();
对象能执行哪些方法主要看左边,和右边关系不大
但当右边有和左边相同的方法(重写时)运行结果看右边
总结
1.父类引用指向子类的对象
2.子类转父类,向上转型(自动),丢失独有方法
3.父类转子类,向下转型(强制)
4.多态的意义,方便方法的调用,减少重复代码,使代码更加简洁
public static void main(String[] args) {
//类型之间的转化: 父 子
//子类内存比父类的大,子类是1.5父类是1
//子类转换为父类,可能丢失自己的一些特有方法
Student student = new Student();
student.eat();
//低转高,自动转换
Person person = student;
//使用子类方法需要进行转换
((Student)person).eat();
Student person1 = (Student) person;
person1.run();
}

浙公网安备 33010602011771号