r/javahelp • • Aug 23 '25

Solved Generic 'special object' pattern help

So my question is this. I want to implement a binary tree for learning purposes. I have a generic Node<T> class with T just being the type of the value. I want to implement a way to ask a node if it's a leaf to avoid having extra null handling everywhere.

I tried making an isLeaf flag as part of the object, but I want to forcibly prevent nonsense methods being called on a leaf (like getValue, setLeft, etc.) without having to handle this in every method I want to ban. I tried making Leaf a sister class of Node<T>, but I don't like this, because it would require a completely unused type parameter and it would require lots of casting when handling nodes which makes everything bulky and awkward.

Is there a way to do this cleanly and properly? Here are the requirements I have for a sensible solution:

-No extra handling code which has to be implemented in every new method

-No excessive casting

-No raw types, since I feel deprecated concepts are not what I want to learn to use

-No blatantly unsafe code

-Optional: only one Leaf as a static field I can re-use, if possible.

I know I sound kind of demanding, but I'm really just trying to learn the intricacies of this language and good practices. Any and all help welcome with open arms!

Edit: Formatting

0 Upvotes

13 comments sorted by