多态
- 即同一方法可以根据发送对象的不同而采用多种不同的行为方式。
- 一个对象的实际类型是确定的,但可以指向对象的引用的类型有很多
- 多态存在的条件
- 有继承关系
- 子类重写父类方法
- 父类引用指向子类对象
- 父类和子类能进行类型转换,有联系才能转换------类型转换异常 ClassCastException!
- 存在条件: 继承关系,方法需要重写,父类引用指向子类对象 Father f1 = new Son();
- 注意:多态是方法的多态,属性没有多态性。
- instanceof 判断一个对象是什么类型
//Person为父类,Student为子类
public class Person {
public void print(){
System.out.println("Person");
}
}
public class Student extends Person {
public void print(){
System.out.println("Student");
}
public void eat(){
System.out.println("eat");
}
}
public class Main {
public static void main(String[] args) {
//一个对象的实际类型是确定的
//new Student();
//new Person();
//可以指向的引用类型就不确定了
//Student类型的对象能调用的方法都是自己的或者继承父类的
Student s1 = new Student();
//Person父类型,可以指向子类,但是不能调用子类独有的方法
Person s2 = new Student();
object s3 = new Student();
/*
对象能执行哪些方法,主要看对象左边的类型,和右边关系不大!
如果子类重写了父类的方法,那么执行子类的方法
*/
s1.print(); //输出 Student
s2.print(); //输出 Student
s1.eat(); //输出 Student
s2.eat(); //错误
((Student) s2).eat()//输出 Student 需要强制转换才能调用子类独有的方法
}
}
instanceof
- 编译看左,运行看右
System.out.println(x instanceof Y);//能不能编译通过,取决于x的类型与y是否有父子关系
System.out.println(x instanceof Y);//能不能返回true,取决于x的引用的对象与y是否有父子关系
//若x的引用的对象为y类型的父类,则依旧返回false
Object object = new Student();
System.out.println(object instanceof Student); //true
System.out.println(object instanceof Person); //true
System.out.println(object instanceof object); //true
System.out.println(object instanceof Teacher); //False
System.out.println(object instanceof String); //False
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); //编译报错!
System.out.println("========================");
Student student = new Student();
System.out.println(student instanceof Student); //true
System.out.println(student instanceof Person); //true
System.out.println(student instanceof object); //true
//System.out.println(student ins tanceof Teacher); //编译报错!
//System.out.println(student ins tanceof String); //编译报错!
类型转换
//类型之间的转化: 父 子
// 高 低
//子类转换为父类,可能丢失自己的本来的一些方法!
Student student = new Student();
student.go();
Person person = student;
/*
父类引用可以指向子类的对象,但子类引用不能指向父类对象
例如 假设上面的Student还有一个子类叫做GoodStudent,由于student指向的是Student对象,如果向下转型,就会导致GoodStudent类型的引用指向父类对象,这是不允许的。
把子类转换为父类,向上转型:自动转换
把父类转换为下类,向下转型:强制转换
*/