Re: attribute or subclass
From: Pradyumn Sharma (pradyumnsharma_at_hotmail.com)
Date: 04/28/04
- Next message: christopher diggins: "Re: Adding abstract class..."
- Previous message: Pradyumn Sharma: "Re: Observer: Should messages carry data?"
- In reply to: Gergely Buday: "attribute or subclass"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 28 Apr 2004 01:29:27 -0700
"Gergely Buday" <greg@no-spam.xhvg.hu> wrote in message news:<c68c9o$21m$1@namru.matavnet.hu>...
> I have a class and I would like to have another class that somehow contains
> the original one. There are two ways to achieve this:
>
> - to have the original class as an attribute of the new class
>
> - to derive the new class as the descendant of the original one
>
> Which are the pros and cons of these methods?
>
> - Gergely
There are trade-offs involved. With inheritance the derived class code
is simpler, but with delegation (having a reference to the original
class), you have more flexibility.
Some of the risks with inheritance are:
* Potential violation of the Liskov Substition Principle. If the
derived class (your new class) overrides some functions of the base
class (your original class), and in the process violates some
commitment made by the base class, a client could be adversely
affected by receiving the derived class
reference in place of the base class reference. Function overriding
means risk for clients of the base class.
* If the base class's implementation changes without changing its
contract, and if the derived class implementation has made any
assumptions about the base class implementation, the contract of the
derived class may break.
* Inheritance is a static relationship. If class B inherits from
class A, you cannot change this relationship dynamically. But
delegation is dynamically changeable. If an object of class B has a
reference to an object of class A, at run-time, you can make it point
to some other object of class A, or even some subclass of A, thereby
changing the behaviour of B dynamically. In this situation, ideally, A
should be an interface.
Hope this helps.
Pradyumn Sharma
Pragati Software Pvt. Ltd.
www.pragatisoftware.com
- Next message: christopher diggins: "Re: Adding abstract class..."
- Previous message: Pradyumn Sharma: "Re: Observer: Should messages carry data?"
- In reply to: Gergely Buday: "attribute or subclass"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|