Class structure: How should a binary tree and it's node class be implemented in Java in terms of class files?
https://softwareengineering.stackexchange.com/questions/391569
-
24-02-2021 - |
Pergunta
In implementing a binary tree in Java, should the node class be a separate class file independent of the BinaryTree
class, or should it be a default class in the same class file as the BinaryTree
class?
First Example: Node is in separate class file
BinaryTree.java
public class BinaryTree {
...
}
BinaryTreeNode.java
public class BinaryTreeNode {
...
}
Second Example: Node class is default class in same class file
BinaryTree.java
public class BinaryTree {
....
}
class BinaryTreeNode {
...
}
I almost never see the use case for putting more than one class inside of the same class file, but this might be the first time I see it being useful. Does this make sense, or would this be considered sloppy code?
Solução
The problem with using default (package-protected) classes is that you won't be able to use that class outside of the package. For something like this, you typically want to.
There's a third option that I think is preferable. Use a nested class:
public class BinaryTree {
// ...
public static class Node {
// ...
}
}
Whether you make this a 'static' nested class or not depends on whether you want to implicitly associate each instance with a single parent BinaryTree or want to be able to create Nodes that can exist in 0-to-many trees.
In terms of compilation and usage, the static nested class is just like having a public class called BinaryTreeNode
but with the name BinaryTree.Node
.
There are a few advantages to this. One is that you keep the highly coupled code together in a single file. One really nice thing is that The BinaryTree
can use private methods and values of the Node
and vice-versa So you can keep things really well-encapsulated.