← Back to Perl Course | Chapter 7: Object-Oriented Perl | Lesson 5 of 7

Inheritance की जानकारी

एक subclass को इसकी parent class के methods मिलते हैं और यह इन्हें override या extend कर सकता है।

In this page:

  1. Inheritance

Inheritance

use parent pragma parent को subclass के @ISA array में add करके inheritance set up करता है, जिसे आप सीधे our @ISA = (Parent) से भी assign कर सकते थे। जब object की अपनी class में एक method न मिले, Perl @ISA की classes search करता है। एक overriding method के अंदर, SUPER::method parent का version call करता है।

Note: use parent -norequire, Base तब चाहिए जब parent same file में defined हो, क्योंकि नहीं तो use parent Base.pm नाम की एक file load करने की कोशिश करता है।

उदाहरण: Inheritance

perl
use strict;
use warnings;

package Animal;
sub new {
    my ($class, %args) = @_;
    my $self = bless { name => $args{name} }, $class;
    return $self;
}
sub name  { $_[0]{name} }
sub speak { my $self = shift; return $self->name . " makes a sound"; }

package Dog;
use parent -norequire, 'Animal';
sub new {
    my ($class, %args) = @_;
    my $self = $class->SUPER::new(%args);
    $self->{tricks} = [];
    return $self;
}
sub speak {
    my $self = shift;
    return $self->SUPER::speak() . ": Woof!";
}
sub add_trick { my ($self, $t) = @_; push @{ $self->{tricks} }, $t; return $self; }
sub tricks    { @{ $_[0]{tricks} } }

package main;

my $animal = Animal->new(name => "Generic");
my $dog    = Dog->new(name => "Rex");
print $animal->speak, "\n";
print $dog->speak, "\n";
$dog->add_trick("sit")->add_trick("roll");
print "tricks: ", join(", ", $dog->tricks), "\n";
print "Dog ISA: @Dog::ISA\n";

# Output:
# Generic makes a sound
# Rex makes a sound: Woof!
# tricks: sit, roll
# Dog ISA: Animal
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. same file में defined classes के लिए -norequire भूल जाना
  2. SUPER::new के बिना parent का constructor call करना
  3. यह मान लेना कि SUPER object की class को refer करता है बजाय उस package के जहाँ call लिखा है
चैप्टर सारांश
  • use parent @ISA set करता है
  • Methods parents में search होते हैं
  • SUPER::method parent का version call करता है
  • -norequire एक file load करना skip करता है
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.