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