【发布时间】:2016-11-04 09:11:35
【问题描述】:
在 Perl 中是否可以在不实现构造函数的情况下创建子类?我不需要任何特定于子类的构造函数行为,所以我想从父类继承。
在这个例子中,我有一个基类Base.pm 和一个子类Child.pm。 Child 类应该简单地覆盖其父方法之一:
# test.pl
use strict;
use warnings;
use Child;
my $o = Child->new();
$o->exec();
-
# Base.pm
package Base;
sub new{
my $self = {};
bless $self;
return $self;
}
sub exec{
my $self = shift;
die "I'm in the Base class\n";
}
1;
-
# Child.pm
package Child;
use Base;
@ISA = ('Base');
sub exec{
my $self = shift;
die "OVERRIDE in child\n";
}
1;
当我运行 test.pl 时,基类的 exec 方法被执行(我认为这是因为对象在Base.pm 构造函数中被祝福为Base)。
$ ./test.pl
I'm the Base class
有没有办法实现子类而不必重新实现构造函数?
【问题讨论】:
标签: perl