l Polymorphism
Class a {
2. INT x = 1;
3. INT Y = 2;
4. INT f () {returnx 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
● Means SuperClass's Reference Var can refer to all Subclass's Instance. (Refers to Reference Variable is not Object, as long as it is subtype)
● As 17th line. The 19th journey will generate Compile Error, because Class Z is not Class B's SUBCLASS
Method Invocation
● Virtual Mehhod Invocation is built on Method Overriding and Polymorphic Assignment.
● As 20 lines. Chapter 17 declares a Reference Var "A" of Class A and REFER TO SUBCLASS B.
Compile-Time and Run-Time Type
● Compile-time Type is the Type of Reference Var, and run-time Type is the type of object.
● Chapter 17, compile-time, A is a type, and the Runt-Time is a B Type.
● Chapter 21 Compile Err Since A is A TYPE, it is necessary to transform ((b) a) .g () can be executed.
Overriding and shadowing
● Instance Method can only be overridden, while Class Method and Field can only be shadowed.
● Overriding Instance Method has a so-called Compile Time Type and Run Time Type.
● Shadowing Class Method / Field will always have a type of Type, which is the reference var of Type. ● Chapter 23 lines X and 25 rows sf () are shadowing. Want to see the Reference Var Type (a).
● It is best to change the standard call mode B.SF ().
From: [Garfield's SCJP Read Note]