1

I do have a basic question about inheritance and classes.

How would you create an real world object of a tree (a real tree).

Tree should have branches, branches should have leaves.

So:

class Tree {
// something about a tree itself
}

Class Branch : Tree {
//something about a branch
}

Class Leaf : Branch {
//something about a leaf
}

But now, should a tree class know about all the branches instances and create all the branches objects itself while the branches should create leaves for themselves and also know about them ?

So to just put a tree you would:

Tree myNewTree = new Tree(); // or something like that ? 

I think i got something back to front here... Examples of a shape - > rectangle and you ask for rectangle makes sense.

  • 1
    Inheritance is the wrong approach here. A branch is not a kind of tree, and a leaf is not a kind of branch. – jwodder Apr 16 '15 at 12:38
  • What approach would be appropriate here ? –  Apr 16 '15 at 12:38
  • 1
    Go for Composition instead of Inheritance – user2408578 Apr 16 '15 at 12:41
  • the tree here is an object. you must have only one class. branch and leaf can be either a variable or an array. it depends on your case here. – Fakher Apr 16 '15 at 12:41
  • So, should I have a class of branch and a class of leaf, and then array of branches within a tree data ? –  Apr 16 '15 at 12:44
  • 2
    What you want is *composition* or maybe *aggregation*, not *inheritance*. Take a look at this link [from stack overflow](http://stackoverflow.com/questions/885937/difference-between-association-aggregation-and-composition) or this [tutorial](http://www.codeproject.com/Articles/22769/Introduction-to-Object-Oriented-Programming-Concep#Composition) – Harold Ship Apr 16 '15 at 12:44
  • Thank you @HaroldShip I've looked into those and all is quite clear right now. If a tree would die within all branches and leaves and those branches and leaves only works with a tree that should be composition, but if branches and leaves could live on without a tree for a while that would be aggregation am I right ? –  Apr 16 '15 at 12:58
  • @Tomas you are right. If they do not exist without the tree then composition. If the leaves continue to live without the tree then aggregation. – Harold Ship Apr 16 '15 at 13:41

1 Answers1

0

You can have following structure

class Tree {
// something about a tree itself
        Branch b[];
        Leaf lf[];
}

Class Branch {
    //something about a branch
}

Class Leaf{
  //something about a leaf
}

If you want to restrict Branch and Leaf of type tree then Extend Tree class in above structure and Compose them in your Tree Class according to real world Scenario.

Here i have used array you can use anything else like ArrayList <E> or Simple object depending upon your requirement.

user2408578
  • 464
  • 1
  • 4
  • 13