示例程序

 1 public final class Address
 2 {
 3     private final String detail;
 4     private final String postCode;
 5 
 6     //在构造方法里初始化两个实例属性
 7     public Address()
 8     {
 9         this.detail = "";
10         this.postCode = "";
11     }
12     public Address(String detail , String postCode)
13     {
14         this.detail = detail;
15         this.postCode = postCode;
16     }
17     //仅为两个实例属性提供getter方法
18     public String getDetail()
19     {
20          return this.detail;
21     }
22 
23     public String getPostCode()
24     {
25          return this.postCode;
26     }
27     //重写equals方法,判断两个对象是否相等。
28     public boolean equals(Object obj)
29     {
30         if (obj instanceof Address)
31         {
32             Address ad = (Address)obj;
33             if (this.getDetail().equals(ad.getDetail()) && this.getPostCode().equals(ad.getPostCode()))
34             {
35                 return true;
36             }
37         }
38         return false;
39     }
40     public int hashCode()
41     {
42         return detail.hashCode() + postCode.hashCode();
43     }
44 
45     public static void main(String args[])
46     {
47         Address a = new Address();
48         Address b = new Address("dscfd","fghgh");
49         
50         System.out.println("a:"+a.getDetail()+a.getPostCode()+a.hashCode());
51         
52         System.out.println("b:"+b.getDetail()+b.getPostCode()+b.hashCode());
53         
54         System.out.println(a.equals(b));
55     }
56 }

结果截图

分析:

以final声明的方法不允许覆盖。

以final声明的变量不允许更改。

利用final,我们可以设计出一种特殊的“只读” 的“不可变类”。

 

创建“不可变的类”的对象后,此对象的属性不可改,而且也无法从此类派生出新子类。String就是一个典型的例子。

不可变的“类”有何用?

可以方便和安全地用于多线程环境中, 访问它们可以不用加锁,因而能提供较高的性能。

 JDK中的实例:String

posted on 2015-11-05 11:23  卫平公  阅读(306)  评论(0编辑  收藏  举报