多态
多态:同一方法可以根据发送对象的不同而采用多种不同的行为方式
publicclassPerson{publicvoidrun(){System.out.println("Run");}}publicclassStudentextendsPerson{@Overridepublicvoidrun(){System.out.println("子类");}publicvoideat(){System.out.println("eat");}}测试类
publicclassApplication{publicstaticvoidmain(String[]args){//一个对象的实际类型是确定的//new Student();//new Person();//可以指向的引用类型不确定:父类的引用指向子类//Student能调用的方法都是自己的或者继承父类的Students1=newStudent();//Person 父类,可以指向子类,但是不能调用子类独有的方法Persons2=newStudent();Objects3=newStudent();//对象能执行哪些方法,主要看对象左边的类型,和右边关系不大s2.run();s1.run();s1.eat();((Student)s2).eat();//s2.eat();//子类重写了父类的方法,执行子类的方法}}注意:
多态是方法的多态,属性没有多态
父类和子类有联系 类型转换异常 ClassCastException
存在条件:继承条件,方法需要重写,父类引用指向子类对象 Father f1=new Son();
以下方法不能被重写
- static方法,属于类,不属于实例
- final常量
- private方法
instanceof
instanceof(类型转换)引用类型,判断一个对象是什么类型
publicclassStudentextendsPerson{@Overridepublicvoidrun(){System.out.println("子类");}publicvoideat(){System.out.println("eat");}publicvoidgo(){System.out.println("go");}}publicclassApplication{publicstaticvoidmain(String[]args){//一个对象的实际类型是确定的//new Student();//new Person();//可以指向的引用类型不确定:父类的引用指向子类//Student能调用的方法都是自己的或者继承父类的Students1=newStudent();//Person 父类,可以指向子类,但是不能调用子类独有的方法Persons2=newStudent();Objects3=newStudent();//对象能执行哪些方法,主要看对象左边的类型,和右边关系不大s2.run();s1.run();s1.eat();((Student)s2).eat();//s2.eat();//子类重写了父类的方法,执行子类的方法//Object>String//Object>Person>Teacher//Object>Person>Student//System.out.println(X instanceof Y);//能不能编译通过!Objectobject=newStudent();System.out.println(objectinstanceofStudent);//trueSystem.out.println(objectinstanceofPerson);//trueSystem.out.println(objectinstanceofObject);//trueSystem.out.println(objectinstanceofTeacher);//falseSystem.out.println(objectinstanceofString);//falseSystem.out.println("==============================");Personperson=newStudent();System.out.println(personinstanceofStudent);//trueSystem.out.println(personinstanceofPerson);//trueSystem.out.println(personinstanceofObject);//trueSystem.out.println(personinstanceofTeacher);//false//System.out.println(person instanceof String);//编译报错Studentstudent=newStudent();System.out.println(studentinstanceofStudent);//trueSystem.out.println(studentinstanceofPerson);//trueSystem.out.println(studentinstanceofObject);//true//System.out.println(student instanceof Teacher);//编译报错//System.out.println(person instanceof String);//编译报错//类型之间的转化:父类>子类//基本类型转换 高低64 32 16 8//高转低要强转//高 低Personobj=newStudent();//obj.go();//报错//obj将这个对象转换为Student类型,我们就可以使用Student类型的方法了Studentobj1=(Student)obj;obj1.go();//((Student) obj).go();//子类转换为父类,可能丢失自己的本来的一些方法Studentstudent1=newStudent();student1.go();Personperson1=student1;//person1.go();}}多态条件:父类引用指向子类的对象
把子类转换为父类,向上转型,自动的,但可能会丢失一些方法
把父类转换为子类,向下转型,需要强制转换
方便方法的调用,减少重复的代码