K
K
Kolos902015-11-03 00:02:48
Java
Kolos90, 2015-11-03 00:02:48

Why is such an initialization of the object, according to the author of the book, considered correct?

The Java Philosophy book by Bruce Eckel states the following:
The output of the program shows (code below) that the w3 reference bypasses the double initialization, before and during the constructor call. (The first object is lost, and eventually the garbage collector will destroy it.) This may seem inefficient at first, but this approach guarantees correct initialization - which would happen if the class had an overloaded constructor that did not initialize the w3 reference, but it would when it wouldn't get the default value?

//: initialization/OrderOfInitialization.java
// Demonstrates initialization order.
import static net.mindview.util.Print.*;

// When the constructor is called to create a
// Window object, you'll see a message:
class Window {
  Window(int marker) { print("Window(" + marker + ")"); }
}

class House {
  Window w1 = new Window(1); // Before constructor
  Window w2 = new Window(2); // After constructor
  Window w3 = new Window(3); // At end 

  House() {
    // Show that we're in the constructor:
    print("House()");
    w3 = new Window(33); // Reinitialize w3
  }

  void f() { print("f()"); }

}

public class OrderOfInitialization {
  public static void main(String[] args) {
    House h = new House();
    h.f(); // Shows that construction is done
  }
} /* Output:
Window(1)
Window(2)
Window(3)
House()
Window(33)
f()
*///:~

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Moseychuk, 2015-11-03
@Kolos90

class House {
  House(int i) {
    print("House(int)");
  }
  Window w3; // Not Init!
  House() {
    // Show that we're in the constructor:
    print("House()");
    w3 = new Window(33); // initialize w3
  }
  Window w2 = new Window(2); // After constructor
  void f() { print("f()"); }
  Window w1 = new Window(3); // At end 
}

Now you have 2 constructors. And depending on which one to call, w3 will be initialized or not.
And in your code, w3 will be initialized in any case, if the reference is not explicitly nullified in the constructor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question