Parent class references to subclass objects

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.