2011年11月16日 星期三

[Java] Object Initialization - (1)

An object is a chunk of memory bundled with the code that manipulates memory.

* The Java language has three mechanisms dedicated to ensuring proper initialization of objects:
(Instance initializers and instance variable initializers collectively are called "initializers.")
  • Instance initializers (also called instance initialization blocks)
  • Instance variable initializers
  • Constructors.
class CoffeeCup {
    private int innerCoffee = 100;
    //...
}

Note
If you explicitly initialize innerCoffee, say to a value of 100, then when each CoffeeCup object is created, innerCoffee will, in effect, be initialized twice.
  1. innerCoffee will be given its default initial value of zero.
  2. The zero will be overwritten with the proper initial value of 100.
All of this takes place while the Java virtual machine is creating the new object -- before it returns the reference to the new object.


* The difference between methods and constructors:
  • The name of a class is a valid name for its methods.
  • Constructors aren't methods by showing that a constructor does not conflict with a method that has the same signature.


* Default constructors
  • If you declare a class with no constructors, the compiler will automatically create a default constructor for the class.
  • Takes no parameters (it's a no-arg constructor) and has an empty body.
  • All classes are guaranteed to have at least one constructor.
  • The compiler gives default constructors the same access level as their class.


* Instance initialization methods
  • When you compile a class, the Java compiler creates an instance initialization method for each constructor you declare in the source code of the class.
  • Although the constructor is not a method, the instance initialization method is
    • It has a name, <init>
    • A return type, void,
    • A set of parameters that match the parameters of the constructor from which it was generated.
    • Not a valid Java method name, so you could not define a method in your source file that accidentally conflicted with an instance initialization method. 
    • Is not a method in the Java language sense of the term, because it has an illegal name. In the compiled, binary Java class file, however, it is a legal method.
If you don't explicitly declare a constructor in a class, the Java compiler will create a default constructor on the fly, then translate that default constructor into a corresponding instance initialization method. Thus, every class will have at least one instance initialization method.


* Initializers

  • Besides providing constructors, Java offers one other way for you to assign an initial value to instance variables: initializers (instance variable initializers and instance initializers).
  • In an instance variable initializer, you have only an equals sign and one expression.
    • private int innerCoffee = 355; // "= 355" is an initializer
    • The right-hand side of the equals sign in an initializer can be any expression that evaluates to the type of the instance variable.


* Instance initializers
Java 1.1 introduced the instance initializer, which is also called the instance initialization block.

// The following block is an instance initializer
    {
        innerCoffee = 355;
    }

Instance initializers are a useful alternative to instance variable initializers whenever:
(1) initializer code must catch exceptions, or
(2) perform fancy calculations that can't be expressed with an instance variable initializer.

Advantages
  • Can just write the code once.
    • You could, of course, always write such code in constructors. But in a class that had multiple constructors, you would have to repeat the code in each constructor.
  • Will be executed no matter what constructor is used to create the object.
  • Useful in anonymous inner classes, which can't declare any constructors at all.


* Initializers can't make forward references

參考物件的順序是無法顛倒,得依照宣告的先後,因此使用了還未宣告到的變數是不可行的,會被報錯,如下:

class VirtualCafe {
    private int chairsCount = 4 * tablesCount;
    private int tablesCount = 20;
    //...
}
但有些寫法,仍能通過,如下:
class VirtualCafe {

    private int chairsCount = initChairsCount();
    private int tablesCount = 20;

    private int initChairsCount() {
        return tablesCount * 4;
    }
    //...
}
  • Here chairsCount's initializer sneakily invokes a method that uses tablesCount before its initializer has been executed.
  • When initChairsCount() calculates tablesCount * 4, tablesCount is still at its default initial value of zero.
  • As a result, initChairsCount() returns zero, and chairsCount is initialized to zero.



* Reference
- Object Initialization in Java ***

沒有留言:

張貼留言