Polymorphism is not very easy for students with poor foundations. Let's talk about my understanding of it. It is opposite to inheritance. inheritance is the sub-class that calls the parent class, while polymorphism is the sub-class used by the parent class. In inheritance, subclasses can use common methods and attributes in the parent class. In polymorphism, in short, a parent class object is created, its content can be of the parent class or its subclass. When the subclass has the same function as the parent class, when this object is used to call this function, A function with the same name in the class (that is, the parent class) that defines this object will be called. When the function in the parent class is prefixed with the virtual keyword or the parent class as an interface, then the sub-class function with the same name will be called.
Below is a section of C # code to explain Polymorphism
Class test {staticvoid main (string [] ARGs) {testtt = new test (); TT. playvideo ();} public voidplayvideo () {videoshowvw; vw = newdvd (); console. writeline (VW. playvideo (); vw = newvcd (); console. writeline (VW. playvideo () ;}} public abstractclass videoshow {publicabstract stringplayvideo ();} public class VCD: videoshow {publicoverride stringplayvideo () {return "playing VCD ";}} public class DVD: videoshow {publicoverride stringplayvideo () {return "playing a DVD ";}}
In the above Code, we use the parent class videoshow to instantiate an object VW. Below we use the parent class object to call the method playvideo In the subclass.
From polymorphism, we also introduced the concepts of upward and downward Transformation:
Downward Transformation: The parent class may not be converted to a subclass type.
Upward Transformation: Sub-classes must be converted to parent classes.
An image example is as follows:
Polymorphism: Java programmers include j2se, J2EE, and j2s.
Upward Transformation: Turning J2EE into a Java programmer
Downward Transformation: Converting Java programmers into J2EE