1 public class test {2/** 3 * For polymorphism, it can be summarized as: 4 5 I. Use the reference of the parent class to point to the object of the subclass; 6 2. The reference can only call methods and variables defined in the parent class. 8 9 3. If a method in the parent class is rewritten in the subclass, when this method is called, this method in the subclass will be called; (dynamic connection, dynamic call) 10 11 4. Variables cannot be overwritten (overwrite). The concept of "Overwrite" is only for methods, if a variable in the parent class is "overwritten" in the subclass, an error is reported during compilation. 12 13 three necessary conditions for Polymorphism: 14 15 1. inherit 2. Override 3. parent class reference points to subclass object. 16 * @ Param args17 */18 public static void main (string [] ARGs) {19 a B = new B (); 20 B. printn (); // 421 B. printm (); // 422 system. out. println (B. n); // 023 system. out. println (B. m); // 024 25 B Ba = (B) B; 26 Ba. printn (); // 427 Ba. printm (); // 428 system. out. println (BA. n); // 429 system. out. println (BA. m); // 430 31 B bb = new B (); 32 BB. printn (); // 433 BB. printm (); // 434 system. out. println (BB. n); // 435 system. out. println (BB. m); // 436} 37 38} 39 40 class A {41 int n = 0; 42 static int m = 0; 43 public void printn () {44 system. out. println (n); 45} 46 47 Public void printm () {48 system. out. println (m); 49} 50} 51 Class B extends a {52 int N = 4; 53 static int M = 4; 54 public void printn () {55 system. out. println (n); 56} 57 public void printm () {58 system. out. println (m); 59} 60}
Parent class references to subclass objects