Java:references initialized
If you want the references initialized,you can do it:
1.At the point the objects are defined.This means that they'll always be initialized before the constructor is called
2.In the constructor for the class
3.Right before you actually need to use the object.This is often called lazy initialization. It can reduce overhead in situations where object creation is expensive and the object doesn't need to be created every time.
4.Using instance initialization
All four approachs are shown here:
1 class Soap { 2 private String s; 3 4 Soap() { 5 System.out.println("Soap()"); 6 s = "constructed"; 7 } 8 9 public String toString() { 10 return s; 11 } 12 } 13 14 public class Bath { 15 private String // Initializing at point of definition 16 s1 = "Happy", 17 s2 = "happy", 18 s3, s4; 19 private Soap castille; 20 private int i; 21 private float toy; 22 23 public Bath() { 24 System.out.println("inside Bath()"); 25 s3 = "joy"; 26 toy = 3.14f; 27 castille = new Soap(); 28 } 29 30 // Instance initialization 31 { 32 i = 47; 33 } 34 35 public String toString() { 36 if (s4 == null)// Delayed initialization 37 s4 = "joy"; 38 return "s1=" + s1 + "\n" + 39 "s2=" + s2 + "\n" + 40 "s3=" + s3 + "\n"+ 41 "s4=" + s4 + "\n" + 42 "i=" + i + "\n" + 43 "toy=" + toy + "\n"+ 44 "castille=" + castille + "\n"; 45 } 46 47 public static void main(String[] args) { 48 Bath b = new Bath(); 49 System.out.println(b); 50 } 51 }
输出
1 inside Bath() 2 Soap() 3 s1=Happy 4 s2=happy 5 s3=joy 6 s4=joy 7 i=47 8 toy=3.14 9 castille=constructed
Note that in the Bath constructor,a statement is executed before any of the initializations take place. When you don't initialize at the point of definition, there is still no guarantee that you'll preform any initialization before you send a message to an object reference--except for the inevitable runtime exception.
When toString() is called it fills in s4 so that all the fields are properly initialized by the time they are ued.