K
Koszalek Opalek
Hello,
A method in the base class can be overridden in the derived class.
My question is: can an _object_ override a method in its base class?
Here is a simple class P with two methods: new() and meth(). I would
like to create an object of class P that uses its own method meth().
#!/usr/bin/perl
use strict;
use warnings;
{
package P;
sub new
{
my $class = shift;
my $self = {@_};
bless $self, $class;
return $self;
};
sub meth
{
my $self = shift;
print "This is a class method.\n";
};
};
my $obj = P->new(
meth => sub { print "This is an object method.\n" }
);
$obj->meth;
The code above will (obviously) print
This is a class method.
I would like it to call the sub defined in the object $obj and print
This is an object method.
I came up with the following solution (this is a new implementation
of method meth() in the class P):
sub meth
{
my $self = shift;
if ($self->{meth}) {
&{$self->{meth}};
} else {
print "This is a class method.\n";
};
};
Is there a more elegant way?
K.
A method in the base class can be overridden in the derived class.
My question is: can an _object_ override a method in its base class?
Here is a simple class P with two methods: new() and meth(). I would
like to create an object of class P that uses its own method meth().
#!/usr/bin/perl
use strict;
use warnings;
{
package P;
sub new
{
my $class = shift;
my $self = {@_};
bless $self, $class;
return $self;
};
sub meth
{
my $self = shift;
print "This is a class method.\n";
};
};
my $obj = P->new(
meth => sub { print "This is an object method.\n" }
);
$obj->meth;
The code above will (obviously) print
This is a class method.
I would like it to call the sub defined in the object $obj and print
This is an object method.
I came up with the following solution (this is a new implementation
of method meth() in the class P):
sub meth
{
my $self = shift;
if ($self->{meth}) {
&{$self->{meth}};
} else {
print "This is a class method.\n";
};
};
Is there a more elegant way?
K.