Reputation: 1211
I came across the code below, and was wondering if each Tree instance would be referencing a different EMPTY object, or if it would reference the same object for all tree instances (only be instantiated once).
class Tree<T> {
public final Tree<T> EMPTY = new EmptyTree<T> ();
/** True iff THIS is the empty tree. */
public boolean isEmpty () { return false; }
private static class EmptyTree<T> extends Tree<T> {
/** The empty tree */
private EmptyTree () { }
public boolean isEmpty () { return true; }
}
...
}
My intuition was that it would have to be 'public static final....' for only one object to be initialized across the class for EMPTY.
From page 99-100 of Data Structures Into Java
Upvotes: 1
Views: 74
Reputation: 140525
You are correct. This code uses a new EMPTY object each time.
Which is of course valid, but not the "normal" thing to do. Of course, I am on of those people that say that static is actually an abnormality within good OO design; but the Java language allows to use static; and (unless there are good reasons within code not shown here) ... the reasonable way would be to have a shared static EMPTY Tree constant.
But that code looks strange anyway - what is the "sense" in having an isEmpty()
method that returns always false for example?!
My "intuition" here: I would step back and do a full review of that code in order to understand if there are "more" surprises within that class.
Upvotes: 4