What is polymorphism in Java

Java-Tutorial.org

Polymorphism

Methods can be subject to so-called polymorphism. Polymorphism is Greek and means diversity. In Java, for example, one speaks of polymorphism when two classes use the same method name but the implementation of the methods is different. Often, polymorphism is used in inheritance; This means that not only objects of the type of the class specified in the declaration can be assigned to a variable, but also objects of the type of the child classes. This only works because each child class must also implement all the methods and attributes of its parent classes.

This ensures that all child classes have the same methods as the parent class. The methods can, however, be implemented in different ways; this is referred to as "overwriting" the method.

Example:

importjava.io. *; abstractclass pen {string write color; publicabstractvoid give pen color out ();} class ballpoint pen extends pen {public ball pen (string e) {write color = e;} publicvoid give pen color out () {System.out.println ("the pen color of the pen is" + write color + " , \ n ");}} class Buntstift extends pen {public Buntstift (String e) {write color = e;} publicvoid give write color out () {System.out.println (" My colored pencil has the write color "+ write color +", \ n ");}} publicclass StiftTester {publicstaticvoid main (String [] args) throwsIOException {/ * ballpoint pen object is assigned to a variable that points to an object of the parent class" pen "* / pen some pen = new ballpoint pen (" blue " ); / * Method "giveWritingColorOff" of the class ballpoint pen is executed * / any pen. outputWriteColorOut (); / * Crayon object is assigned to a variable that points to an object of the parent class "Pen" * / anyPen = new Crayon ("red"); / * Method "giveWritingColorOut" of class Crayon is executed * / anyPen. outputWriteColorOut ();}}

Objects of the subclasses "Ballpoint pen" and "Colored pencil" are assigned to a variable that points to an object of the parent class "Pen". Since all classes have the method "give writing color off", calling the method "give writing color off" is not a problem. The JVM knows which class is hidden behind the object of the variable "any pen". So now the method "giveWriting ColorOut" of the object of the respective subclass (i.e. pencil or ballpoint pen) is called, but not that of the pen class.

With the call of "any pen.getClass ()" you can "look at" the class of the object to which the variable "any pen" points:

System.out.println (anyPen.getClass ());

If, however, no change in functionality is required for the child class, the implementation of the parent method can also be taken over by using the keyword Super (Reference to instance of parent class) is called. However, this is not possible in the above example because the method of the parent class is abstract there, i.e. it has not yet been implemented.