1

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

Rdesmond
  • 1,201
  • 10
  • 30

1 Answers1

4

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 1
    Correct Answer. Generally true in Java with one exception: String interning. Some implementations of Java may recycle `String` objects rather than always instantiate a fresh object. See: http://stackoverflow.com/q/10578984 – Basil Bourque Nov 28 '16 at 20:53
  • It's from a textbook; I added part of the EmptyTree class which EMPTY is referencing. The text says that "There is only one empty tree (guaranteed because the EmptyTree class is private to the Tree class, an example of the Singleton design pattern), but this tree is a full-fledged object..." so I was confused because it seemed (if I've provided the relevant code) like many instances would be created without 'static', and that the Singleton pattern only allows one global object to be created. (sorry if I'm being pedantic; I try to be as clear as possible when confused about something) – Rdesmond Nov 28 '16 at 21:13