java中final關鍵字

來源:互聯網
上載者:User

標籤:public   常量池   als   改變   rgs   strong   end   []   編譯   

在Java中,final關鍵字可以用來修飾類、方法和變數(包括成員變數和局部變數)。下面就從這三個方面來瞭解一下final關鍵字的基本用法。

1.修飾類

   當用final修飾一個類時,表明這個類不能被繼承。final類中的成員變數可以根據需要設為final,final類中的所有成員方法都會被隱式地指定為final方法。

2.修飾方法

 final修飾的方法,方法不能被重寫(可以重載多個final修飾的方法)。當父類中final修飾的方法同時存取控制許可權為private,子類中不能直接繼承到此方法,此時子類中定義相同的方法名和參數,為子類中重新定義了新的方法。

3.修飾變數

  1) final修飾變數表示常量,只能被賦值一次,賦值後值不再改變。如果final修飾一個參考型別時,值指的是地址的值,內容是可變的。

public class Test06 {    public static void main(String[] args){        Test06 test = new Test06();        final StringBuilder str = new StringBuilder("hello");        str.append("World");        System.out.println(str);            }}

  輸出結果為helloWorld。

  2)當final變數是基礎資料型別 (Elementary Data Type)以及String類型時,如果在編譯期間能知道它的確切值,則編譯器會把它當做編譯期常量使用。

  編譯期間能知道它的確切值:

public class Test06 {    public static void main(String[] args)  {         String a = "helloworld";           final String b = "hello";         String d = "hello";         String c = b + "world";           String e = d + "world";         System.out.println((a == c));         System.out.println((a == e));     } }

  輸出結果為true,false;編譯器將其當成常量,a,c都指常量池中的"helloworld"。

 

  編譯期間不知道它的確切值:

public class Test06 {    public static void main(String[] args)  {         String a = "helloworld";           final String b = getWord();         String d = "hello";         String c = b + "world";           String e = d + "world";         System.out.println((a == c));         System.out.println((a == e));     }     public static String getWord() {         return "hello";     } }

  輸出結果為false,false。

java中final關鍵字

聯繫我們

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