When one class uses another as its base, and then overrides it, you want that behavior. Sometimes it would be nice for the parent class to be able to take control, but if that where the case then you would have a hard time subclasses other peoples modules to make them do what you want. Realy you just need to look at the problem differently. Since you are making objects you want to think about the actual objects, not the classes. The classes are just a template to build objects with. So your 'person' class isn't 'Alice', it is just a template you are going to use to make the object that will be 'Alice'. In the same fashion your 'child' class isn't 'Billy the kid', it is just a template for an object that has a name, and knows its parents. So when you create the child object you want to tell it it's name and then tell it who its parents are by passing its parents to it as objects. I have modified your code to do exactly that below.
#!/usr/bin/perl use strict; { package person; #basic person sub new { my ($class, $name) = @_; my $self = { 'name' => $name }; bless $self, $class; return $self; } sub tellName { my ($self) = $_[0]; return $self->{'name'}; } sub introduce { my ($self) = $_[0]; print "Hello, I'm ", $self->tellName(), "\n"; } } { package child; #person + ability to know parents our @ISA = qw(person); # inherits from person sub new { my ($class, $name, $mom, $dad) = @_; my $self = $class->SUPER::new($name); $self->{mom} = $mom; $self->{dad} = $dad; bless $self, $class; return $self; } sub introduce { my($self)=$_[0]; $self->SUPER::introduce(); for (qw/mom dad/) { if ($self->{$_}) { print "Here's my $_: ", $self->{$_}->tellName(); } } } } package main; my $mom = new person("Alice"); $mom->introduce(); # that time it works. print "\n"; my $son = new child("Fred", $mom); $son->introduce();
The important thing to notice is that the child package is building on the provided definition of a person, adding to that person the ability to remember who its parents are. The packages themselves hold no data, only the objects will hold data. I think partly your use of default names is confusing the issue between class (the description) and the object (what is created using the description as a template). If your person class was able to call its own 'tellName' instead of the inherited one, then you would never have a way to override the behavior of tellName which is exactly the point of inheritance! ;) I hope this helps you.
In reply to Re^2: my $self is stumped!
by eric256
in thread my $self is stumped!
by headybrew
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |