"Java Fundamentals" "Tenth Lesson" polymorphism

Source: Internet
Author: User

Java's polymorphic usage is basically the same as C + +.

Look at the code.

1  Public classTen2 {3      Public Static voidMain (string[] args)4     {5Human guest =NewHuman ();6Brokencup Hiscup =NewBrokencup ();7 8         //Although the parameters of the function drink in human are one Cup,9         //but the polymorphic mechanism determines that it calls a brokencup that inherits from the Cup.TenGuest.drink (Hiscup, 10); One     } A  - } -  the classHuman - { -     voidDrink (Cup Acup,intW) -     { + Acup.drinkwater (w); -     } + } A  at //Water Cup - classCup - { -     Private intWater = 0; -  -      Public voidAddwater (intW) in     { -          This. Water = This. Water +W; to     } +  -      Public voidDrinkwater (intW) the     { *          This. Water = This. Water-W; $     }Panax Notoginseng } -  the //Broken Cup + classBrokencupextendsCup A { the     //overriding the methods of the parent class +      Public voidAddwater (intW) -     { $System.out.println ("Shit, broken Cup"); $     } -  -      Public voidDrinkwater (intW) the     { -System.out.println ("Oh, no water inside");Wuyi     } the}

The output is:

Oh, no water inside

To summarize:

1. In Java, all classes inherit from the object class. The object class provides methods such as ToString (). We can override these methods in our own class definitions.

2. We can transform a base class reference downward (downcast) into a reference to a derived class, but require that the base class reference point to the object that is already the derived class object to be downcast. For example, the above hiscup can be transformed upward into a cup class reference, and then down into the Brokencup class reference.

"Java Fundamentals" "Tenth Lesson" polymorphism

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.