"Joe" <
[email protected]> wrote in message
news:
[email protected]...
> In article <[email protected]>, (e-mail address removed)
> says...
> > Hi,
> > Appology if silly question but can you have a class which extends more
than
> > one other class?
> > If so what is the correct syntax?
> > eg class1 needs to extend class2 & class3
> > thanks
> > Ian.
>
>
> Just to step outside of the sctrictly Java-centric answer, you should ask
> why you need to inherit two classes. Inheritance means you have an 'is-a'
> relationship. For instance, the Dog class would inherit the Mammal class
> because a dog is a Mammal. If you find that Dog needs to also inherit
> HouseholdPet, maybe HouseholdPet should inherit Mammal and Dog inherits
> HouseholdPet instead. It's unusual for a class to *NEED* to inherit two
> classes in a well-designed system. Of course, if you're saddled with
> someone else's code, sometimes you can't help it.
This really is not a good example. What if you have a lizard that is also a
HouseholdPet? It would not make sense for it to inherit from Mammal.
Multiple inheritance has a lot of problems, and people who think they need
it probably should rethink the entire problem. In this case, you probably
need the concept of a "Role" of HouseholdPet, which can be filled by a Dog
or Lizard. You could then also have a "WildPredator" role which could be
filled by either.
A more real-world example would be a University, which has Students and
Employees. Both are members of the class Person, with names, birth date and
so on. You might envision a Student subclass with course schedules and
GPAs, and an Employee subclass with work schedules and salaries. This is
all fine, until you hire a grad student as a teaching assistant. Now which
is he...a Student or an Employee? You could solve this with multiple
inheritance, but can get ugly if both Student and Employee have a
"getSchedule" method. Our TA has both a work schedule and a course
schedule, and how does the object know which one to return?
In my opinion, inheritance should only be used for representing immutable
characteristics of an object, not for things that can come and go during the
life of the system. Defining Student and Employee as roles which are
temporarily filled by a person is a better solution.
--
Jim McMaster
mailto: (e-mail address removed)