We all know that "mammals have many kinds of sounds", such as: "roar", "howl", "woof", "meow", etc. These are the polymorphisms of sounds.
So when a class has many subclasses, and these subclasses all override a method in the parent class, when we put the reference of the object created by the subclass into an object of the parent class, we get the An upcast object of the object. At this time, the upcast object may have polymorphism when calling this method, because different subclasses may produce different behaviors when overriding the parent class's methods.
For example: when the up-transformed object of the dog class calls the "bark" method, the behavior generated is "woof", while when the up-transformed object of the cat class calls the "bark" method, the behavior produced is "meow" and so on.
Polymorphism means that when a method of the parent class is overridden by its subclass, each can produce its own functional behavior.
For example:
class animal {voidcry(){}} class dog extends animal {voidcry(){System.out.println(wangwang);}} class cat extends animal {voidcry(){System.out.println(miaomiao);}} publicclassMain {publicstaticvoidmain(Stringargs[]){animal;animal=new dog();animal.cry();animal=new cat();animal.cry();}}
The running results are as follows:
wangwangmiaomiao