Re: inheritance vs containment
- From: Arne Vajhøj <arne@xxxxxxxxxx>
- Date: Thu, 20 Jan 2011 17:23:35 -0500
On 20-01-2011 12:45, mp wrote:
it seems i've seen articles warning against excessive use of inheritance
"is a" vs "has a"
i think this is a sample of "is a" ... i don't know how i'd make it a "has
a" sample
Stock "is a" Investment.
Investment "has a" Name.
That is not a particular good example because it is
not so likely that people would have Investment inherit
from Name or String (the last is not even possible in .NET
because String is sealed).
But you would be surprised how often you see a developer
want to inherit from a completely unrelated class just
to get its methods.
public class Investment : MyFancyPersistingUtils
would be such an example.
i was thinking to try a simple inheritance like the following
public class Investment
{
public Investment()
{ }
public Investment(string name)
{
_name = name; //,<<every investment would have a name
}
public string Name { get; set; }
}
class Stock : Investment
{
public string Ticker { get; set; }//,< stocks have ticker symbol
}
class RealEstate : Investment
{
public string Address { get; set; }//<< houses have address
}
is that sort of how inheritance works?
Yes.
ie save having to add multiple definitions of name in each subclass
That is just a side effect.
The purpose of it is that you can treat Stock and RealEstate
as Investment.
F.ex. storing them in a List<Investment>.
and would deriving from investment like that affect xmlSerializing
a list of subtypes
I don't get that.
other problems/advantages of this type of structure?
See above.
Arne
.
- References:
- inheritance vs containment
- From: mp
- inheritance vs containment
- Prev by Date: Re: inheritance vs containment
- Next by Date: Re: inheritance vs containment
- Previous by thread: Re: inheritance vs containment
- Next by thread: How is used Linq on a DataView object?
- Index(es):
Relevant Pages
|