码迷,mamicode.com
首页 > 编程语言 > 详细

Java:The final Keyword

时间:2015-04-23 21:39:34      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

 

 1 import java.util.*;
 2 
 3 class Value {
 4     int i;
 5 
 6     public Value(int i) {
 7         this.i = i;
 8     }
 9 }
10 
11 public class FinalData {
12 
13     private static Random rand = new Random(47);
14     private String id;
15 
16     public FinalData(String id) {
17         this.id = id;
18     }
19     //can be compile-time constants:
20     private final int valueOne = 9;
21     private static final int VALUE_TWO = 99;
22     //Typical public constant:
23     public static final int VALUE_THREE = 39;
24     //cannot be compile-time constants
25     private final int i4 = rand.nextInt(20);
26     static final int INT_5 = rand.nextInt(20);
27     private Value v1 = new Value(11);
28     private final Value v2 = new Value(22);
29     private static final Value VAL_3 = new Value(33);
30     private final int[] a = { 1, 2, 3, 4, 5, 6 };
31 
32     public String toString() {
33         return id + ": i4 = " + i4 + ", INT_5 = " + INT_5;
34     }
35 
36     public static void main(String[] args) {
37         FinalData fd1 = new FinalData("fd1");
38         //!fd1.valueOne++; //Error:cannot change value
39         fd1.v2.i++;//Object is not constant
40         fd1.v1 = new Value(9);//OK--not final
41         for (int i = 0; i < fd1.a.length; i++) {
42             fd1.a[i]++; //Object is not constant
43         }
44         //!fd1.v2=new Value(0); //Error:cannot
45         //!fd1.VAL_3=new Value(1);//change reference
46         //!fd1.a=new int[3];
47         System.out.println(fd1);
48         System.out.println("creating new FinalData");
49         FinalData fd2 = new FinalData("fd2");
50         System.out.println(fd1);
51         System.out.println(fd2);
52     }
53 }

输出

fd1: i4 = 15, INT_5 = 18
creating new FinalData
fd1: i4 = 15, INT_5 = 18
fd2: i4 = 13, INT_5 = 18

 

Java:The final Keyword

标签:

原文地址:http://www.cnblogs.com/taoxiuxia/p/4451751.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!