l Polymorphism
1. class A{
2. int x = 1;
3. int y = 2;
4. int f() { return x; }
5. static char sf() { return ‘A’; }
6. }
7. class B extend A{
8. int x = 3; // shadowing
9. int z = 4;
10. int f() { return x; } // overriding
11. static char sf() { return ‘B’;} //shadowing
12. int g(){ int x = 1; return (x+this.x); }
13. }
14. class Z extend A{ }
15. public class SCJP {
16. pubilc static void main(String[] args){
17. A a = new B();
18. B b = new B();
19. B bb = new Z(); //error
20. System.out.println(a.f()); // 3
21. System.out.println(a.g()); // error
22. System.out.println(a.z); // error
23. System.out.println(a.x); // 1
24. System.out.println(a.y); // 2
25. System.out.println(a.sf()); // ‘A’
26. System.out.println(b.x); // 3
27. System.out.println(b.sf()); // ‘B’
28. } }
Assignment | ● 意思是superclass的reference var可以refer to所有subclass的instance。(指的是reference variable不是object,只要是subtype就可以) ● 如第17行。第19行會產生compile error,因class Z不是class B的subclass |
Method Invocation | ● virtual mehhod invocation,建立在method overriding及polymorphic assignment上。 ● 如第20行。第17行宣告一個class A的reference var “a”並refer to subclass B。 |
Compile-time and Run-time Type | ● compile-time type是reference var的type,run-time type是object的type。 ● 第17行,compile-time時a是A type,runt-time時a是B type。 ● 第21行compile err因為此時a為A type,需轉型為 ((B)a).g() 才可以被執行。 |
Overriding and Shadowing | ● instance method只能被overridden,而class method及field只能被shadowed。 ● overriding instance method才有所謂的compile time type及run time type。 ● shadowing class method / field 永遠只有一種type,就是reference var的type。 ● 第23行x和第25行sf()是shadowing。要看reference var的type (A)。 ● 第27行最好改為標準呼叫方式B.sf()。 |
来自:【 Garfield 的 SCJP 閱讀筆記 】