package Base;
# Base class to experiment with private and protected methods
use warnings;
use strict;
use Carp;
sub new {
my $type = shift;
my $class = ref $type || $type;
my $self = {
TEXT => undef,
SECRET => undef,
NOTSOSECRET => undef,
};
my $closure = sub {
my $field = shift;
if (@_) { $self->{$field} = shift; }
return $self->{$field};
};
bless ($closure,$class);
return $closure;
}
# a public accessor to set TEXT
sub text { &{ $_[0] }("TEXT", @_[1 .. $#_]) }
# a private accessor to set SECRET
sub private {
caller(0) eq __PACKAGE__ || confess "private method";
&{ $_[0] }("SECRET", @_[1 .. $#_]);
}
# a public accessor to set SECRET by means of the private method
sub secret {
private($_[0],@_[1 .. $#_]);
}
# a protected accessor to set NOTSOSECRET
sub protected {
caller(0)->isa(__PACKAGE__) || confess "protected method\n";
&{ $_[0] }("NOTSOSECRET", @_[1 .. $#_]);
}
1;
####
package Inherit;
# Inherit class to experiment with private and protected methods
use warnings;
use strict;
use Base;
use vars qw(@ISA);
@ISA = qw(Base);
sub inheritSecret {
$_[0]->private(@_[1 .. $#_]);
}
sub inheritNotSoSecret {
$_[0]->protected(@_[1 .. $#_]);
}
1;
##
##
#!/usr/bin/perl
use warnings;
use strict;
use Base;
use Inherit;
my $base = Base->new();
$base->text("hello");
print $base->text . "\n";
my $inherit = Inherit->new();
$inherit->text("howdy");
print $inherit->text . "\n";
$base->secret("secret");
print $base->secret . "\n";
# this will get us an error saying private method
#$inherit->inheritSecret("verySecret");
#print $inherit->inheritSecret . "\n";
# impossible to access protected directly
#$inherit->protected("notsosecret");
#print $inherit->protected . "\n";
# access to NOTSOSECRET by means of a protected method
$inherit->inheritNotSoSecret("notsosecret");
print $inherit->inheritNotSoSecret . "\n";