Your general model actually makes a lot of sense. You have identified the duplicate code and separated it from the class. Using generics helps maintain cleanliness. Is it worth it to explicitly select the layers of the tree (for which it essentially is), since Subchapters, Chapters, etc. Depend on your exact requirements.
It may be easier to simply identify the nodes and leaves of the tree, but if you need different behavior at each level and donโt need the flexibility to add or remove more layers, then this is normal. Consider, for example, if you ever have an omnibus with Omnibus-> Book-> Chapter-> Subchapter-> Paragraph or a book with a book-> Chapter-> Section-> Chapter-> Paragraph. Could your model support them? If it is not necessary?
Some names may be clearer (for example, nr as a number) or may not conform to style conventions (the name should be a heading).
The main mistake, I would say, is to save the number inside the object in general. This is fragile because it means that you constantly have to update it when things are added, deleted, etc.
You can always find out the number simply by looking at the position in the parent. In essence, you are duplicating this information.
As Grigori noted in the comments, all variables must be private and accessible through getters and setters.
Tim b source share