This article is mainly about the "Java programming thought" to see things, is the seventh chapter of the beginning of the re-use of the class, mainly the class initialization of the location of several methods, mainly including
1. Where the object is defined. This means that they are always initialized before the constructor is called.
2. In the constructor of the class
3. This approach is called lazy initialization before you want to use these objects. This approach reduces the additional burden of generating objects that are not worthwhile and do not have to generate objects every time.
4. Use instance initialization.
Here are some examples of these four ways.
1 classsoap{2 PrivateString S;3 Soap () {4System.out.println ("Soap ()");5s = "constructed";//initializing in the constructor6 }7 PublicString toString () {8 returns;9 }Ten } One A Public classbath{ - PrivateString S1 = "Happy", s2 = "Hello";//defining the local initialization of an object - PrivateString S3, S4; the PrivateSoap Castile; - Private inti; - PublicBath () { -Print ("Bath ()"); +S3 = "Tonny"; - } + A{i = 43;}//using instance initialization at - PublicString toString () { - if(S4 = =NULL) -S4 = "John";//Lazy Initialization - return"Done"; - } in}
In Bath (), a line of statements is executed before all initialization is made, and if not initialized at the definition, there is no guarantee that the information will be initialized before it is sent to the object reference unless an unavoidable run-time exception occurs.
Initialization methods in Java