Java:references initialized

來源:互聯網
上載者:User

標籤:

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 definition16             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 initialization31     {32         i = 47;33     }34 35     public String toString() {36         if (s4 == null)// Delayed initialization37             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=Happy4 s2=happy5 s3=joy6 s4=joy7 i=478 toy=3.149 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. 

Java:references initialized

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.