Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 6

Polymorphism

Polymorphism

Polymorphism is the ability of an object to take on many forms.

Most common use of polymorphism in OOP occurs when a parent


class reference is used to refer to a child class object.

A simple example explains this concept.

To make use of this feature, functions or tasks must be declared


with virtual keyword in the base class. Only on adding virtual it
allows the subclasses to override the behavior of the function or
task.

If we need to add to the behavior of the function or task in base


class, then we must call super.task or super.function in the
subclass task or function.

Example

virtual class Shape; // Abstract base class


pure virtual function int unsigned area(); // No implementation
endclass : Shape

class Circle extends Shape;


int unsigned radius;
virtual function int unsigned area(); // Derivatives of Circle can
override this.
return PI * radius * radius; // Assume PI is a global constant
defined somewhere.
endfunction : area
endclass : Circle

class Triangle extends Shape;


int unsigned base, height;
function int unsigned area(); // Derivatives of Triangle cannot
override this.
return (base * height) / 2;
endfunction : area
endclass : Triangle

program main;
Shape s[2]; // Base handles.
Circle c = new;
Triangle t = new;
initial begin
c.radius = 3;
t.base = 9;
t.height = 12;
s[0] = c;
s[1] = t;
$display("The area of the circle is %0d.", s[0].area());
$display("The area of the triangle is %0d.", s[1].area());
end
endprogram : main

The answer is 28 and 54

You might also like