final 與static final修飾變數區別

來源:互聯網
上載者:User
1.import java.util.Random;  2.  3.//這個例子想說明一下static final 與 final的區別  4.public class StaticAndFinalTest {  5.      6.    private static Random rand = new Random(47); //47作為隨機種子,為的就是產生隨機數。  7.      8.    private final int a = rand.nextInt(20);  9.      10.    private static final int B = rand.nextInt(20);  11.  12.    public static void main(String[] args) {  13.        StaticAndFinalTest sf = new StaticAndFinalTest();  14.        System.out.println("sf : " + "a=" + sf.a);  15.        System.out.println("sf : " + "B=" + sf.B);  16.        System.out.println("------------------------------");  17.        StaticAndFinalTest sf1 = new StaticAndFinalTest();  18.        System.out.println("sf1 : " + "a=" + sf1.a);  19.        System.out.println("sf1 : " + "B=" + sf1.B);  20.    }  21.  22.}  

  

運行結果:

  • sf : a=15 
  • sf : B=18 
  • -------------- 
  • sf1 : a=13 
  • sf1 : B=18 

    可以看到,在sf和sf1對象中,a的值不是唯一的,但B的值是不會通過建立sf1對象而改變。這是因為它是static,在裝載時已被初始化,而不是每次建立新對象時都初始化。

聯繫我們

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