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这个类型传入的。

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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM