joh*_*doe 2 oop perl class subclass superclass
我不知道这是否可行,但我想从Perl调用一个已知的子类函数.我需要一些"通用"来称呼更具体的东西.我的超类将假设所有子类的类都定义了已知的函数.我想这与Java"implements"类似.
例如,假设我有以下代码:
GenericStory.pm
package Story::GenericStory;
sub new{
my $class = shift;
my $self = {};
bless $self, class;
return $self;
}
sub tellStory {
my $self;
#do common things
print "Once upon a time ". $self->specifics();
}
Run Code Online (Sandbox Code Playgroud)
Story1.pm
package Story::Story1;
use base qw ( Story::GenericStory );
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
return $self;
}
sub specifics {
my $self;
print " there was a dragon\n";
}
Run Code Online (Sandbox Code Playgroud)
Story2.pm
package Story::Story2;
use base qw ( Story::GenericStory );
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
return $self;
}
sub specifics {
print " there was a house\n";
}
Run Code Online (Sandbox Code Playgroud)
#
MAIN
my $story1 = Story::Story1->new();
my $story2 = Story::Story2->new();
#Once upon a time there was a dragon.
$story1->tellStory();
#Once upon a time there was a house.
$story2->tellStory();
Run Code Online (Sandbox Code Playgroud)
编辑:
代码工作正常.我只是忘记了"我的自我=转变"; 在tellStory();
你的代码工作得很好(模数琐碎的错误); 您可能想要添加超类:
sub specifics {
require Carp;
Carp::confess("subclass does not implement required interface");
}
Run Code Online (Sandbox Code Playgroud)
或类似的.