Java polymorphic Example

Source: Internet
Author: User

Three necessary conditions for polymorphic existence
First, to have inheritance;
Second, to have a rewrite;
The parent class reference points to the subclass object.

Code section:

classA { PublicString Show (D obj) {return("A and D"); }     PublicString Show (A obj) {return("A and a"); }}classBextendsA { PublicString Show (B obj) {return("B and B"); }     PublicString Show (A obj) {return("B and A"); }}classCextendsB {}classDextendsB {}

And then I started thinking:

 Public Static voidMain (string[] args) {A A1=NewA (); A A2=NewB (); b b=NewB (); C C=NewC (); D d=NewD ();        System.out.println (A1.show (A1));        System.out.println (A1.show (A2));        System.out.println (A2.show (A1));        System.out.println (A2.show (A2));        System.out.println (B.show (A1));        System.out.println (B.show (A2));        System.out.println (C.show (A1));        System.out.println (C.show (A2));        System.out.println (D.show (A1));        System.out.println (D.show (A2)); System.out.println ("Split Line **************************************");        System.out.println (A1.show (b));        System.out.println (A1.show (c));        System.out.println (A1.show (d));        System.out.println (A2.show (b));        System.out.println (A2.show (c));        System.out.println (A2.show (d));        System.out.println (B.show (b));        System.out.println (B.show (c));        System.out.println (B.show (d));        System.out.println (C.show (b));        System.out.println (C.show (c));    System.out.println (C.show (d)); }

Operation Result:

A and AA and AB and AB, and AB and AB and AB, and AB and AB and A split line **************************************
   
    a and AA and AA and DB and AB and AA and DB and BB and BA and DB and BB and BA and D
   

For ease of understanding, I have listed the method table for each class

b.show(A)

Java polymorphic Example

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.