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