动态编译:类型
即同一个方法可以根据发送对象的不同而采用多种不同的行为方式
一个对象的实际类型是确定的,但可以指向对象的引用的类型有很多(父类,有关系的类)
存在的条件
有继承关系
子类重写父类方法
父类引用指向子类对象
public class Person {
public void run(){
System.out.println("run");
}
}
public class S*tudent extends Person{
?
注意事项:
是方法的多态,属性没有多态
父类和类,有联系 类型转换异常 ClassCastException
存在条件: 继承关系 方法需要重写 父类引用指向子类子类对象
Father f1 = new Son();
static 方法 属于类, 它不属于实例
final 常量
private
引用类型,判断一个对象是什么类型。两个类之间是否存在父子关系
System.out.println(x instanceof y);
能不能编译通过,
看右边的实际类型和要比较的类型 x指向的实际类型是不是y的子类
//继承关系
//object > string
//object > person > teacher
//object > person > student
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
System.out.println("-------------------------");
?
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);//编译报错
?
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 instanceof Teacher);//编译报错
// System.out.println(student instanceof String);//编译报错
?
//Person p = new Person();
System.out.println(p instanceof Person); // true
System.out.println(p instanceof Student); // false
?
//类型之间的转换:父 子
//子类转换为父类 可能丢失自己的本来的方法
//高 低
Person obj = new Student();
//obj.go();
//obj 将这个对象转换为student类型,我们就可以使用Student类型的方法了
?
//Student student = (Student)obj;
//student.go();
((Student)obj).go();
?
//
Person p2 = new Person();
Student s2 = (Student) p2; // runtime error! ClassCastException!
//p2转型为Student会失败,因为p2的实际类型是Person,不能把父类变为子类
?
Student student = new Student();
Person person = student;
person.go();//报错
1.只能父类引用指向子类的对象
2.把子类转换为父类 向上转型,直接转,丢失子类中原本可直接调用的特有方法
3.把父类转换为子类 向下转型 强制转 会丢失父类被子类重写的方法 向下转型很可能会失败。失败的时候,Java虚拟机会报ClassCastException
。
原文:https://www.cnblogs.com/flypigggg/p/14525141.html