Java:The final Keyword

來源:互聯網
上載者:User

標籤:

 

 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 constants25     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 value39         fd1.v2.i++;//Object is not constant40         fd1.v1 = new Value(9);//OK--not final41         for (int i = 0; i < fd1.a.length; i++) {42             fd1.a[i]++; //Object is not constant43         }44         //!fd1.v2=new Value(0); //Error:cannot45         //!fd1.VAL_3=new Value(1);//change reference46         //!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 = 18creating new FinalDatafd1: i4 = 15, INT_5 = 18fd2: i4 = 13, INT_5 = 18

 

Java:The final Keyword

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.