向上转型:

Untitled

向下转型

Untitled

3)不完全对,当前目标类型的对象以及其子类都可。

原理是,强制类型转换: (类型)引用,这要求 引用的运行时是(类型)的子类:即某一个对象,他可以被他的父类引用。

Untitled

直接读属性时,是编译类型的属性。但是重写的方法去读属性时,是看运行时类型。

package fanxin;

public class shuxing {
    int x = 10;
    int getx(){
        return x;
    }
    public static void main(String[] args) {
        shuxing x = new sub();
        System.out.println(x.x);//10,x的运行时类型虽然是sub,但是访问属性还是会访问编译类型的属性
        System.out.println(((sub)x).x);//20
        System.out.println(x.getx());//20
        System.out.println(((sub)x).getx());//20
    }

}

class sub extends shuxing{
    int x= 20;
    int getx(){
        return x;
    }
}

instanceof是看运行时类型

Untitled

因此,

package chapter5;
class Person{

}

class Teacher extends Person{
    void teach(){
        System.out.print("I am a teacher");
    }
}

class Student extends Person{
    void study(){
        System.out.print("I am a student");
    }
}

public class dynamicbinding {
    public static void main(String[] args) {
        Person[] person = new Person[2];
        person[0] = new Teacher();
        person[1] = new Student();
//如果person中有teach方法,可直接:
//        person[1].teach;
//如果没有呢,需要:

        for(int i = 0;i<person.length;i++){
            if(person[i] instanceof Teacher){
                ((Teacher)person[i]).teach();
            }
            else if(person[i] instanceof Student){
                ((Student)person[i]).study();
            }
        }
    }
}

 

Untitled