真实世界树的继承示例

Inheritance example of a real world tree

我确实有一个关于继承和 classes 的基本问题。

您将如何创建树的真实世界对象(一棵真实的树)。

树有枝,枝有叶。

所以:

class Tree {
// something about a tree itself
}

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

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

但是现在,树 class 应该知道所有分支实例并自己创建所有分支对象,而分支应该为自己创建叶子并且也知道它们吗?

因此,如果只放一棵树,您会:

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

我想我在这里得到了一些东西...形状示例 - > 矩形,你要求矩形是有道理的。

你可以有以下结构

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

Class Branch {
    //something about a branch
}

Class Leaf{
  //something about a leaf
}

如果你想限制树的分支和叶子,那么在上面的结构中扩展树 class 并根据现实世界的场景将它们组合在你的树 Class 中。

这里我使用了数组,您可以根据需要使用其他任何东西,例如 ArrayList 或简单对象。