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. 

转载于:https://www.cnblogs.com/taoxiuxia/p/4445026.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值