目的
run-time type と compile-time type の違いを理解する。
該当のソースコード
java
1class Parent { 2 public static void myStaticMethod() { 3 System.out.println("A"); 4 } 5 public void myInstanceMethod() { 6 System.out.println("B"); 7 } 8} // End of the Parent class 9public class Child extends Parent { 10 public static void myStaticMethod() { 11 System.out.println("C"); 12 } 13 public void myInstanceMethod() { 14 System.out.println("D"); 15 } 16 public static void main(String[] args) { 17 Parent o1 = new Parent(); 18 Parent o2 = new Child(); 19 Child o3 = new Child(); 20 Parent.myStaticMethod();// A 21 Child.myStaticMethod(); // C 22 o1.myStaticMethod(); // A 23 o1.myInstanceMethod(); // B 24 o2.myStaticMethod(); // A ★ 25 o2.myInstanceMethod(); // D ☆ 26 o3.myStaticMethod(); // C 27 o3.myInstanceMethod(); // D 28 myStaticMethod(); // C 29 } // End of main method 30} // End of the Child class
###説明文
Notice that o2.myStaticMethod invokes Parent.myStaticMethod(). If this method were truly overridden,we should have invoked Child.myStaticMethod, but we didn't. Rather, when you invoke a static method, even if you invoke it on an instance, you really invoke the method associated with the "compile-time type" of the variable. In this case, the compile-time type of o2 is Parent. Therefore, we invoke Parent.myStaticMethod(). However, when we execute the line o2.myInstanceMethod(), we really invoke the method Child.myInstanceMethod(). That's because, unlike static methods, instance methods CAN be overridden. In such a case, we invoke the method associated with the run-time type of the object. Even though the compile time type of o2 is Parent, the run-time type (the type of the object o2 references) is Child. Therefore, we invoke Child.myInstanceMethod rather than Parent.myInstanceMethod().
質問
上記の説明に、★はcompile-time type を見ているから出力が”A"になると書いてあり、☆はrun-time type を見ているから”D"になると書いてあるのですが、このcompile-time type とrun-time typeの明確な違いがわかりません。これらの明確な違いを教えてください。
回答1件
あなたの回答
tips
プレビュー