Java——静态类型 实际类型

public class test {
    static class father {
        void run() {
            System.out.println("father run");
        }
    }
    static class son extends father{
        void run() {
            System.out.println("son run");
        }
    }

    public void sayHello(son son) {
        System.out.println("son");
    }

    public void sayHello(father father) {
        System.out.println("father");
    }

    public static void main(String[] args) {
        father a = new son();
        a.run();
        test t = new test();
        t.sayHello(a);
        System.out.println(a.getClass());
    }
}

输出结果:

son run
father
class old.test$son

解释:

father a = new son()

这里面 father 是静态类型,son是实际类型。

静态类型是在编译期可知的,而实际类型是在运行期才可以知道,

所以当运行run()时,取的是子类方法,而将a作为参数传入时,是以father这个类型传入的。

这也说明了重写载是静态的,而重写是动态的。

猜你喜欢

转载自www.cnblogs.com/gaoquanquan/p/10991058.html
今日推荐