Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

OOP Design Issue 1

Status
Not open for further replies.

golcarlad

Programmer
Nov 23, 2004
232
GB
I have an abstract class which specifies an abstract getter/setter property. Lets say it should return type "Tree", but in my derived classes I want it to return a more specific Tree type e.g. Redwood, Oak, etc, but they still inherit from Tree - this of course doesnt work because its too strongly typed. Is there a way round this?

Regards (Hope that makes sense BTW!!)

See example code below to see what I mean:

Code:
//THIS IS THE BASE ABSTRACT CLASS
public abstract class Forest
{
    public abstract Tree PropertyTree
    {
        get;
        set;
    }
}

//THIS IS THE DERIVED ACTUAL CLASS
public class MyForest: Forest
{
    private OakTree _oakTree; //OAKTREE INHERITS FROM TREE CLASS!!! V.IMPORTANT

    public override OakTree PropertyTree
    {
         get { return _oakTree; }
         set { _oakTree = value; }
    }
}
 
You shouldn't return OakTree, you should return Tree - which happens to be an OakTree.

In a perfect abstract case, you shouldn't care what type of tree it is that you're passing. FedEx doesn't care if you're shipping a desk or a table, they just know it's a box with a weight and contents.
 
Youre right - I should return a Tree, but the thing is, OakTree has some other methods that a normal Tree doesnt have, so when I loop through Trees, I can never see these unless I do a cast to a more specific tree - I take it thats just the way you have to do it??
 
That's it - casting is a bit slow so limit the amount you do it.

Sometimes you can pre-specify which type of tree it is and put it in an OakTree collection. This way you would only have to cast it once and you could use it throughout your application as an OakTree.
 
OK, well thats cleared a few things up. Cheers
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top