The Wayback Machine - https://web.archive.org/web/20240629223759/https://www.geeksforgeeks.org/perl-polymorphism-in-oops/
Open In App

Perl | Polymorphism in OOPs

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Polymorphism is the ability of any data to be processed in more than one form. The word itself indicates the meaning as poly means many and morphism means types. Polymorphism is one of the most important concepts of object-oriented programming languages. The most common use of polymorphism in object-oriented programming occurs when a parent class reference is used to refer to a child class object. Here we will see how to represent any function in many types and many forms. In a real-life example of polymorphism, a person at the same time can have different roles to play in life. Like a woman, at the same time is a mother, a wife, an employee and a daughter. So the same person has to have many features but has to implement each as per the situation and the condition. Polymorphism is considered as one of the important features of Object Oriented Programming.

Polymorphism is the key power of object-oriented programming. It is so important that languages that don’t support polymorphism cannot advertise themselves as Object-Oriented languages. Languages that possess classes but have no ability of polymorphism are called object-based languages. Thus it is very vital for an object-oriented programming language. It is the ability of an object or reference to take many forms in different instances. It implements the concept of function overloading, function overriding and virtual functions. 

Polymorphism

Polymorphism

Polymorphism is a property through which any message can be sent to objects of multiple classes, and every object has the tendency to respond in an appropriate way depending on the class properties.

This means that polymorphism is the method in an object-oriented programming language that does different things depending on the class of the object which calls it. For example, $square->area() will return the area of a square, but $triangle->area() might return the area of a triangle. On the other hand, $object->area() would have to calculate the area according to which class $object was called. Polymorphism can be best explained with the help of the following example: 

Perl




use warnings;
 
# Creating class using package
package A;
 
# Constructor creation
sub new
{
  
    # shift will take package name 'vehicle'
    # and assign it to variable 'class'
    my $class = shift;
    my $self = {
                  'name' => shift,
                  'roll_no' => shift
               };
     
    sub poly_example
    {
      print("This corresponds to class A\n");
    }
};
 
package B;
 
# The @ISA array contains a list
# of that class's parent classes, if any
my @ISA = (A);
 
sub poly_example
{
  print("This corresponds to class B\n");
 
}
 
package main;
 
B->poly_example();
A->poly_example();


Output:
  
For the first output, For the first output, the method poly_example() defined in class B overrides the definition that was inherited from class A and vice-versa for the second output. This enables to add or extend the functionality of any pre-existing package without re-writing the entire definition of the whole class again and again. Thus making it easy for the programmer.

Polymorphism is the ability of objects to take on different forms or behave in different ways depending on the context in which they are used. In object-oriented programming (OOP), polymorphism is achieved through the use of inheritance, interfaces, and method overriding.

In Perl, polymorphism is primarily achieved through method overriding, which allows a derived class to provide its own implementation of a method defined in the base class. This allows objects of the derived class to be used interchangeably with objects of the base class, without the calling code having to know the specific type of object being used.

Here’s an example of polymorphism in Perl using method overriding:

Perl




#!/usr/bin/perl
# your code here
#!/usr/bin/perl
 
# Define a base class
package Shape;
sub new {
    my $class = shift;
    my $self = {};
    bless $self, $class;
    return $self;
}
 
# Define a method in the base class
sub draw {
    my ($self) = @_;
    print "Drawing a shape\n";
}
 
# Define a derived class
package Circle;
use base qw(Shape);
 
# Override the draw method in the derived class
sub draw {
    my ($self) = @_;
    print "Drawing a circle\n";
}
 
# Define another derived class
package Square;
use base qw(Shape);
 
# Override the draw method in the derived class
sub draw {
    my ($self) = @_;
    print "Drawing a square\n";
}
 
# Create objects of the derived classes
my $circle = Circle->new();
my $square = Square->new();
 
# Call the draw method on the objects
$circle->draw();
$square->draw();


Output

Drawing a circle
Drawing a square

In this example, we define a base class Shape with a draw method. We then define two derived classes Circle and Square, both of which inherit from the Shape class and override the draw method with their own implementation. Finally, we create objects of the Circle and Square classes and call the draw method on them, demonstrating polymorphism in action.



Previous Article
Next Article

Similar Reads

Perl | Objects in OOPs
Perl is an Objected Oriented, dynamic and interpreter based programming language. In object-oriented programming, we have three main aspects, which are, object, class, and methods. An object is a data type which can be specifically called as an instance of the class to which it belongs. It can be a collection of data variables of different data typ
6 min read
Perl | Inheritance in OOPs
Inheritance is a key concept in object-oriented programming that allows you to define a new class based on an existing class. The new class, called a subclass or derived class, inherits all of the properties and methods of the existing class, called the superclass or base class, and can also define its own unique properties and methods. In Perl, in
7 min read
Perl | Method Overriding in OOPs
In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method
6 min read
Object Oriented Programming (OOPs) in Perl
Object-oriented programming: As the name suggests, Object-Oriented Programming or OOPs refers to languages that uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on
7 min read
Perl | Methods in OOPs
Methods are used to access and modify the data of an object. These are the entities which are invoked with the use of objects of a class or a package itself. Methods are basically a subroutine in Perl, there is no special identity of a method. Syntax of a method is the same as that of a subroutine. Just like subroutines, methods are declared with t
5 min read
Perl | Encapsulation in OOPs
Encapsulation in Perl is the process of wrapping up of data to protect it from the outside sources which need not have access to that part of the code. Encapsulation is a part of the Object-oriented programming, it is used to bind the data and the subroutines that are used to manipulate that data. In a different way, encapsulation is a protective s
6 min read
Perl | Basic Syntax of a Perl Program
Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar
10 min read
Perl | chomp() Function
The chomp() function in Perl is used to remove the last trailing newline from the input string. Syntax: chomp(String) Parameters: String : Input String whose trailing newline is to be removed Returns: the total number of trailing newlines removed from all its arguments Example 1: C/C++ Code #!/usr/bin/perl # Initialising a string $string = &quo
2 min read
Perl | Backtracking in Regular Expression
In Perl, a Regular expression(a.k.a regexes or regexps or REs) is a way of describing a set of strings without having to list all strings in your program or simply we can say that it is a sequence of characters that are used for pattern matching. In Perl, regular expressions have different uses: Firstly, they are used in conditionals to determine w
3 min read
Perl | Searching in a File using regex
Prerequisite: Perl | Regular Expressions Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to host language and are not the same as in PHP, Python, etc. Sometimes these are termed as "Perl 5 Compatible Regular Expressions". To use the Regex, Bindi
6 min read
Article Tags :
three90RightbarBannerImg