# inheritance in perl

sub newaccount
{
   my $balance = $_[0];  # now I want this to be a "protected" variable

   my $inquiry = sub { $balance };
   my $deposit = sub { $balance = $balance + $_[0]; };

   my $chargefee = sub { $balance -= 3; };
   my $withdraw = sub 
		  { $balance = $balance - $_[0]; &$chargefee(); };
  
   my $setbal = sub { $balance = $_[0]; };  # "protected" method

   my ($public, $protected);

   $public = sub
   {
     my $method = $_[0]; # requested method
     if ($method eq withdraw) { return $withdraw; }
     if ($method eq deposit)  { return $deposit; }
     if ($method eq inquiry)  { return $inquiry->(); }
     if ($method eq inherit)  { return $protected; }
       else { die "error"; }
   };

   $protected = sub
   {
     my $method = $_[0]; # requested method
     if ($method eq setbal) { return $setbal; }     
     else { $public->($method); }
   };

   $public;
}


# want savings account with an interestrate field.

sub newsavingsaccount
{
    my ($balance, $interest) = @_;
    my $super = newaccount($balance)->(inherit);

    # trouble: want to define "addinterest"

#    my $addinterest = sub { $balance += $interest; }

    # the problem here is that the balance I'm changing is not
    # the same balance as in the $super object!  I would have to
    # define a "set" method in the superclass that allows its
    # balanced variable to be changed externally:

    my $addinterest = 
       sub { $super->(setbal)->($super->(inquiry)+$interest); };

    # How do we get around this problem?  We can use a hash table
    # instead of an interface function, or we can add another method
    # into the superclass that allows one to change the balance.  In
    # either case, however, we'll in effect be making balance PUBLIC!

    # We can try to solve this problem by defining two different 
    # interfaces for the super-object - one for "public" access, and
    # one for "protected" access by subclasses.  The "setbal" function
    # will then only be accessible through the protected interface.

}

# how can we make this more convenient?  Would it be better to have a
# language that automates what I had to build from scratch in Perl?
