Perl

Does Perl have polymorphism? What is method overriding?

Difficulty: unrated

Source: bregman-arie/devops-exercises by Arie Bregman

Answer

Yes, it has polymorphism. In fact method overriding is a way to apply it in Perl.

Method overriding in simple words appears when we have a class with a method that already exist in a parent class.

Example:

package A;

sub new { return bless {}, shift; };
sub printMethod { print "A\n"; };

package B;

use parent -norequire, 'A';

sub new { return bless {}, shift; };
sub printMethod { print "B\n"; };

my $a = A->new();
my $b = B->new();

A->new()->printMethod();
B->new()->printMethod();

# Output:
# A
# B