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 in its super-class, then the method in the subclass is said to override the method in the super-class.

Method Overriding means that the code comprises of two or more methods with the same name but each of them has a special task and that to differ from each other. Thus taking the literal meaning of the name itself it means that one method has to override another. This concept stands for redefining a base class method in its derived class with the exact same method signature.

Method overriding is one of the ways by which Perl achieves Run Time Polymorphism. The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.

Method overriding in Perl can be best explained with the help of the following example:

We have a base class vehicle with the methods: get_mileage() and get_cost() and the derived class car with the methods: get_mileage() and get_age(). Now since one of the methods of both the classes has the same name thus their execution will take place on the principle of the Method Overriding concept. Let’s look into the example and see how they get executed.

  • Creation of Base class:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Declaration and definition of Base class
    use strict;
    use warnings;
      
    # Creating parent class
    package vehicle;
      
    sub new
    {
      
        # shift will take package name 'vehicle' 
        # and assign it to variable 'class'
        my $class = shift;
          
        my $self = {
                    'distance'=> shift,
                    'petrol_consumed'=> shift
                   };
          
        # Bless function to bind object to class
        bless $self, $class;
          
        # returning object from constructor
        return $self;
    }
      
    # Method for calculating the mileage
    sub get_mileage
    {
        my $self = shift;
          
        # Calculating result
        my $result = $self->{'distance'} /
                     $self->{'petrol_consumed'};
                       
        print "The mileage by your vehicle is: $result\n";
        
    }
       
    # Method for calculating the cost
    sub get_cost
    {
        my $self = shift;
          
        # Calculating result
        my $result = $self->{'petrol consumed'} * 70;
          
        print "The cost is: $result\n";
    }
    1;

    chevron_right

    
    

  •  

  • Creation of Derived Class:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Declaring and defining derived class
      
    # Creating derived class
    package car;
       
    use strict;
    use warnings;
       
    # Using parent class
    use parent 'vehicle';
       
    # Overriding the method
    sub get_mileage
    {
        my $self = shift;
          
        # Calculating the result
        my $result = $self->{'distance'} /
                     $self->{'petrol_consumed'};
                       
        print "The mileage by your car is: $result";
    }
      
    # Function to get age from user
    sub get_age
    {
        my $self = shift;
          
        # Taking input from user
        my $age = <>;
          
        # Printing the age
        print "Age is: $age\n";
    }
    1;

    chevron_right

    
    

  •  

  • Using objects to illustrate the process of Method Overriding:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Calling the objects and
    # the methods of each class 
    # using the corresponding objects.
      
    use strict;
    use warnings;
      
    # Using the derived class as parent
    use car;
      
    # Object creation and initialization
    my $ob1 = vehicle -> new(2550, 170);
    my $ob2 = car -> new(2500, 250);
       
    # Calling methods using Overriding
    $ob1->get_mileage();
    $ob2->get_mileage();

    chevron_right

    
    

Output:

As seen that the method from the class that is being called using the object overrides the other method of the same name but in the different classes. The execution of the ‘get_mileage’ method on the object vehicle prints ‘The mileage by your vehicle is: 15’ through the method which was declared in the class vehicle. Whereas when executing the ‘get_mileage’ on the object of car we get the output ‘The mileage by your car is: 10’ through the method in the class car.

Why Method Overriding?

As stated earlier, overridden methods allow Perl to support run-time polymorphism. Polymorphism is essential to object-oriented programming for one reason: it allows a general class to specify methods that will be common to all of its derivatives while allowing subclasses to define the specific implementation of some or all of those methods. Overridden methods are another way that Perl implements the “one interface, multiple methods” aspect of polymorphism.

Dynamic Method Dispatch(Runtime Polymorphism) is one of the most powerful mechanisms that object-oriented design brings to bear on code reuse and robustness. The ability of existing code libraries to call methods on instances of new classes without recompiling while maintaining a clean abstract interface is a profoundly powerful tool.

Overridden methods allow us to call methods of any of the derived classes without even knowing the type of derived class object.
Thus method overriding makes the programming very easy as there is no need to remember different names while creating different methods instead remembering the processes within the Method is much more important.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.