Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bloch Effective Java - favor static classes over nonstatic - how many instances?

I want to know how many instances of a static member class can be created by the enclosing class. I assume one only, but then the following extract from Bloch doesn't make sense to me.

Quoting Joshua Bloch's Effective Java - Item 22*: Favor static member classes over nonstatic.

A common use of private static member classes is to represent components of the object represented by their enclosing class. For example, consider a Map instance, which associates keys with values. Many Map implementations have an internal Entry object for each key-value pair in the map. While each entry is associated with a map, the methods on an entry (getKey, getValue and setValue) do not need access to the map. Therefore, it would be wasteful to use a nonstatic member class to represent entries: a private static member class is best. If you accidentally omit the static modifier in the entry declaration, the map will still work, but each entry will contain a superfluous reference to the map, which wastes space and time.

He states that the map creates an Entry object for each key-value pair in the map, i.e. multiple instances of the static member class.

So my assumption is wrong! That means my understanding of static member classes is wrong. Everyone knows how a static member variable behaves, the classic static final string for instance - there is only one instance of the object.

Does this mean then that a static member class is not actually instantiated when the enclosing object is instantiated?

Well in that case, what's the point of Map using a static member class for Entry? Why not just use an interface on the API? Every other Collections class could then just provide it's own implementation.

[*] Just realised that it's item 18 in the PDF version of the book I have

like image 296
Adam Avatar asked Jul 25 '14 10:07

Adam


People also ask

Can static class have multiple instances Java?

But in general, yes, a static nested type can be instantiated multiple times.

Which of the following syntaxes would you use to create an object for the static nested?

For example, to create an object for the static nested class, use this syntax: OuterClass. StaticNestedClass nestedObject = new OuterClass. StaticNestedClass();

What is a static nested class in Java?

In Java a static nested class is essentially a normal class that has just been nested inside another class. Being static, a static nested class can only access instance variables of the enclosing class via a reference to an instance of the enclosing class.

How do you create an instance of an inner class in Java?

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.


2 Answers

This is a common misinterpretation of the static keyword.

When you use static with a variable it means there will be only one of these for all objects of this class or something like that.

static Object thereWillBeOnlyOne = new Object();

However, in the context of inner classes it means something completely different. A static inner class has no connection with an object of the enclosing class while a non-static inner class does.


A static inner class:

public class TrieMap<K extends CharSequence, V> extends AbstractMap<K, V> implements Map<K, V> {

  private static class Entry<K extends CharSequence, V> implements Map.Entry<K, V> {

The Map.Entry class used by my TrieMap class does not need to refer to the object that created it so it can be made static to save the unnecessary reference.


A non-static inner class:

public final class StringWalker implements Iterable<Character> {
  // The iteree
  private final String s;
  // Where to get the first character from.
  private final int start;
  // What to add to i (usually +/- 1).
  private final int step;
  // What should i be when we stop.
  private final int stop;

  // The Character iterator.
  private final class CharacterIterator implements Iterator<Character> {
    // Where I am.
    private int i;
    // The next character.
    private Character next = null;

    CharacterIterator() {
      // Start at the start.
      i = start;
    }

    public boolean hasNext() {
      if (next == null) {
        if (step > 0 ? i < stop : i > stop) {
          next = s.charAt(i);
          i += step;
        }
      }
      return next != null;
    }

The CharacterIterator inside a StringWalker object refers to the string to be iterated as s which only exists once in the StringWalker object. I can therefore create many iterators of a StringWalker and they all walk the same string.


Why this weirdness?

This seemingly illogical duality derives from the use of the static keyword in C.

In C you can (or at least used to be able to) do:

void doSomething () {
   static int x = 1;

   if ( x < 3 ) {
   } else {
   }
   x += 1;
}

and each time you called the function, x would be as you left it last time around - incremented in this case.

The concept was that the static keyword indicated that the variable was scopefully enclosed by its enclosing block but semantically enclosed by its parent block. I.e. the above code was roughly equivalent to:

int x = 1;
void doSomething () {
   if ( x < 3 ) {
   } else {
   }
   x += 1;
}

but x was only allowed to be referenced inside the function.

Take that concept forward into Java and things now make a little more sense. A static inner class behaves exactly like it was declared outside the class while a non-static inner bonds much more tightly to its enclosing instance - in fact it can refer to the instance directly.

Also:

class Thing {
   static Object thereWillBeOnlyOne = new Object();

behaves much like

Object thereWillBeOnlyOne = new Object();
class Thing {

if it were legal.

Here endeth the lesson.

like image 82
OldCurmudgeon Avatar answered Oct 07 '22 17:10

OldCurmudgeon


I think the Java team messed up the naming on this one. A static inner class (strictly speaking their correct name is "static nested class") is in no way different from an ordinary class except it has a fancy name (Something.MyClass instead of MyClass) and can be made private (i.e. not instantiable from other classes).

In case of Map, it was solely chosen because the name Map.Entry makes it clear that Entry relates to Map. As you suggest, it would have been perfectly reasonable to just use an ordinary class for this. The only difference is you don't get to write Map.Entry.

I think what they should have done is to use the syntax for "non-static" inner classes (i.e. just class in an enclosing class) for static nested classes, and instead invent a new keyword to create "non-static" inner classes, because it's these that behave different from normal classes. Maybe something like attached class. AFAIK the keyword static was chosen in order to avoid having too many reserved keywords, but I think it just encouraged confusion.

like image 27
Enno Shioji Avatar answered Oct 07 '22 17:10

Enno Shioji