1. Perl
  2. Object Oriented
  3. Class inheritance

Inherit class

This time, I will explain how to inherit other classes.

Inherit other classes

Try inheriting another class. There is something I want you to be careful about. Classes are usually created on a file-by-file basis. If you name the package Componet, save the file containing only that package as Component.pm.

Then call it from the script that wants to use that class. However, for the sake of simplicity, many examples describe multiple classes in a single file.

Consider an example of a Button class that inherits a class called Component that has methods x and y.

Inheritance using @ISA

How does Perl inheritance work? Let's run the following example to illustrate it.

use strict;
use warnings;

# Component class
package Component;
sub x {return 5}


# Button class
package Button;
# Inheritance
our @ISA = ('Component');

sub new {bless {}, 'Button'}

package main;
# Use the button class.
my $button = Button->new;
print $button->x;

If you try running this script, you'll see that it says 5. The important thing is that the Button class doesn't have a method called x, but you can call a method called x.

You can do this because the Component class has a method called x, and the Button class inherits from the Component class.

our @ISA = ('Component');

Please pay attention to the part. This is the part that inherits. To inherit, just assign the name of the class you want to inherit to the package variable @ISA.

package main

You may be worried about that part. This description is not necessary if the class is described separately in a file.

When the script starts, it initially belongs to something called the main package. I do that because it's natural to go back and run the main package when using the Button class.

Related Informatrion