Re: inheritance vs containment



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

.



Relevant Pages

  • Re: Regex question; match
    after opening tag

    ... and find a method for that object that will give you a string. ... toString() looked like it might be relevant to what ... and found that it's a pretty good investment. ... Sherm Pendley ...
    (comp.lang.perl.misc)
  • Re: Seasickness cures !
    ... On 19/04/2011 17:47, Justin C wrote: ... I don't want to make that kind of investment unless I*know* ... You take a bit of bacon rind, tie it to some string, swallow it and use the string to jiggle it up and down. ...
    (uk.rec.sailing)
  • Re: Regex question; match
    after opening tag

    ... That's good news, as it shows that nothing actually went wrong; ... and find a method for that object that will give you a string. ... toString() looked like it might be relevant to what ... and found that it's a pretty good investment. ...
    (comp.lang.perl.misc)
  • Re: LED Christmas Lights
    ... I realize each LED has a huge life, but the contacts could fail. ... Before I make the investment I want to know what I am getting ... string down - but a bad connection will still kill a string (or part ...
    (alt.home.repair)