portcall.blogg.se

Dynamic polymorphism java example
Dynamic polymorphism java example











dynamic polymorphism java example

In the above example, the single interface is the draw () method present in the base class Shape and different tasks are the draw () method present in the subclasses. In other words, user need not to be concerned about which draw () method is executed in order to fulfil its requests. The advantage of polymorphism is that even for such heterogenous collection of different shapes, the general draw () method can be invoked, which automatically results in respective method being called according to the actual type of shape.

dynamic polymorphism java example

With polymorphism, whenever a user wants to draw a particular shape (say circle), it simply sends the request to the super class Shape by invoking its method draw () which in reality be calling a method draw () of the appropriate sub class so as to display the requested shape. As the technique for drawing different shapes is unique so we have redefined (override) the draw () method in each of the subclass. In the above figure, draw() method is present in the base class Shape to draw any shape. The class hierarchy is as shown in the following figure. In order to simulate this, a separate version of draw a shape needs to be implemented for every class that describes a kind of shape (derive class). The user’s request in everyday language to draw a shape will therefore lead to various different actions. Each shape in it may be completely different as eash may be of different structure and have different way of drawing such as rectangle, circle, triangle etc, If we want to draw different shapes, the same task has to be performed in principle (i.e, draw a shape) but depending on the shape, it may look very different as method for drawing each shape is different. In order to understand this concept, consider an example of collection of shapes in a Graphic package. The important points to remember about polymorphism.Characteristics of Polymorphism in Java.

dynamic polymorphism java example

  • Referencing Subclass Object using Superclass Reference Variable.












  • Dynamic polymorphism java example