Open In App

Perl | Inheritance in OOPs

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

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, inheritance is implemented using the “use base” directive. Here’s an example of inheritance in Perl:

Perl




#!/usr/bin/perl
# your code here
#!/usr/bin/perl
 
# Define the Person class
package Person;
 
# Define the constructor
sub new {
    my $class = shift;
    my $self = {
        name => shift,
        age => shift,
        gender => shift
    };
    bless $self, $class;
    return $self;
}
 
# Define the say_hello method
sub say_hello {
    my ($self) = @_;
    print "Hello, my name is $self->{name}.\n";
}
 
# Define the Student class
package Student;
 
# Inherit from the Person class
use base 'Person';
 
# Define the constructor
sub new {
    my $class = shift;
    my $self = $class->SUPER::new(@_);
    $self->{major} = shift;
    return $self;
}
 
# Define the say_hello method
sub say_hello {
    my ($self) = @_;
    print "Hello, my name is $self->{name} and I'm a $self->{major} major.\n";
}
 
# Create a new Person object
my $person = Person->new("John", 25, "Male");
 
# Call the say_hello method on the Person object
$person->say_hello();
 
# Create a new Student object
my $student = Student->new("Mary", 20, "Female", "Computer Science");
 
# Call the say_hello method on the Student object
$student->say_hello();


Output

Hello, my name is John.
Hello, my name is Mary and I'm a Mary major.

In this example, we have defined a “Person” class with a constructor and a “say_hello” method. We then define a “Student” class that inherits from the “Person” class using the “use base” directive. The “Student” class also defines its own constructor and “say_hello” method that includes the student’s major in the output.

Advantages of Inheritance in Perl:

  1. Code Reusability: Inheritance allows you to reuse the code from a base class in a new class, reducing the amount of duplicate code you need to write.
  2. Easy Maintenance: Inheritance makes it easier to maintain and update your code because you can make changes to the base class and have those changes automatically apply to all derived classes.
  3. Polymorphism: Inheritance provides polymorphism, which means that you can use a derived class object in place of a base class object. This can make your code more flexible and adaptable to changing requirements.

Disadvantages of Inheritance in Perl:

  1. Complexity: Inheritance can make your code more complex, especially when you have multiple levels of inheritance. This can make it harder to understand and maintain your code.
  2. Tight Coupling: Inheritance creates a tight coupling between the base class and the derived class, which can make it harder to change the implementation of the base class without affecting the derived class.
  3. Inheritance Hierarchies: Inheritance hierarchies can become too deep and too complex, which can make it hard to understand the relationships between classes and can lead to performance issues.

Overall, inheritance is a powerful tool in Perl that can be used to improve code reusability and maintainability. However, it should be used carefully to avoid introducing unnecessary complexity and tight coupling between classes.

Inheritance is the ability of any class to extract and use features of other classes. It is the process by which new classes called the derived classes are created from existing classes called Base classes. The basic concept here is that the programmer is able to use the features of one class into another without declaring or defining the same thing again and again in different classes. Instead of writing the member functions during every class declaration we can inherit those from the base class. Inheritance is one of the most important feature of Object Oriented Programming. Sub Class: The class that inherits properties from another class is called Sub class or Derived Class. Super Class: The class whose properties are inherited by sub class is called Base Class or Super class

The most basic concept of inheritance is Creating or Der

iving a new class using another class as a base.

Base Class and Derived class

Base class is used to derive additional inherited subclasses known as Derived classes. There can be multiple derived classes from a single base class, such type of inheritance is called Hierarchical Inheritance. These derived classes share a single Parent class or Base class. If a derived class shares multiple Parent classes and inherit its features from multiple parent classes then such kind of inheritance is called Multiple Inheritance. Above image shows the order in which a class is derived from a base class. Whenever there is need to depict the order of inheritance theoretically, the order and the denotations as shown in the above image will be used. Consider a class of Vehicles. Now we need to create a class for Bus, Car, truck, etc. The methods fuelAmount(), capacity(), applyBrakes() will be the same for all of the Vehicles. If we create these classes without the knowledge of inheritance then we might do it the way as shown in the diagram: Above Image shows the creation of these classes without the concept of Inheritance It can be seen clearly that the above process results in duplication of the same code 3 times. This increases the chances of error and data redundancy. To avoid this type of situation, inheritance is used. If we create a class Vehicle and write these three functions in it and inherit the rest of the classes from the vehicle class, then we can simply avoid the duplication of data and increase re-usability. Look at the below diagram in which the three classes are inherited from vehicle class: Using inheritance, we have to write the functions only one time instead of three times as we have inherited the rest of the three classes from the base class(Vehicle).

Multilevel Inheritance

Inheritance in Perl can be of many types but multilevel inheritance is one in which there is a chain of the base class and derived classes. In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class. In the below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C

Implementing Inheritance in Perl:

Inheritance in Perl can be implemented with the use of packages. Packages are used to create a parent class which can be used in the derived classes to inherit the functionalities. 

Perl




use strict;
use warnings;
 
# Creating parent class
package Employee;
 
# Creating constructor
sub new
{
    # shift will take package name 'employee'
    # and assign it to variable 'class'
    my $class = shift;
     
    my $self = {
                'name' => shift,
                'employee_id' => shift
               };
     
    # Bless function to bind object to class
    bless $self, $class;
     
    # returning object from constructor
    return $self;
}
1;


The above code is the definition of the base class. Here the base class is employee with the data members being the employee id and the name of the employee. This code for parent class needs to be saved as *.pm, here we will save it as employee.pm. We’ll now see how to derive a class from the already declared base class employee. 

Perl




# Creating parent class
package Department;
  
use strict;
use warnings;
  
# Using class employee as parent
use parent 'employee';
  
1;


As seen in the above example, the class Department uses the traits of the already declared class employee. So while declaring the class Department we did not declare all the data members again instead inherited them from the base class employee. To run this code, save the intermediatory class code as *.pm, here it is saved as Department.pm. This class is the intermediatory class and will further work as a parent class for the following given derived file data.pl

Perl




use strict;
use warnings;
  
# Using Department class as parent
use Department;
 
# Creating object and assigning values
my $a = Department->new("Shikhar",18017);
  
# Printing the required fields
print "$a->{'name'}\n";
print "$a->{'employee_id'}\n";


Output: Thus inheritance plays a very vital role when working on a big project and the programmer wants to shorten the code.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads