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這個類型傳入的。
這也說明了重寫載是靜態的,而重寫是動態的。