Monday 29 April 2019

What is Polymorphism?

In this post, I am going to explain very basic details about Polymorphism with an example. Basically, Polymorphism is used to redefine or extend the methods of the base classes and this can be achieved by overriding the base class methods using the methods defined in the derived classes. Following are some of the rules to be taken care for Polymorphism.
1) Place "virtual" keyword with method definition in base class which will to be redefined in child class.
2) Method name, number of arguments in the method and type of arguments in the method should be same as base class method in order to override base class method with derived class method.

Let's take an example of method overriding and see the results.

class base;
  virtual function void display();
    $display("BASE Class display method.");
  endfunction 
endclass

class child extends base;
  function void display();
    $display("CHILD Class display method.");
  endfunction 
endclass

module top();
  initial begin
    base b1;
    child c1;
    c1 =new();
    b1 = c1;
    b1.display();
    c1.display();
  end
endmodule

RESULT:
CHILD Class display method.
CHILD Class display method.

If we remove "virtual" keyword from the base class "display()" method definition then base class method will not get overridden and following is the result.

RESULT:
BASE Class display method.
CHILD Class display method.

No comments:

Post a Comment