Java-final關鍵字,

來源:互聯網
上載者:User

Java-final關鍵字,

final:最終的,到此為止

分三種情況:

1、修飾類

表示該類不能被繼承和擴充

final class A {}class B extends A {}// 編譯器報錯,表示無法繼承

2、修飾方法

子類無法覆蓋和重寫該方法

class A {    final void method() {}}class B extends A {    @override    void method() {}// 編譯器報錯,無法重寫該方法}

3、修飾變數

對對象來說,保證變數的引用不變,其值可以被修改

對基本類型資料時,保證值不變。修飾方法參數時也是一樣

public class FinalDemo {    public static void main(String[] args) {        String a = "Hello2";        final String b = "Hello";        String c = b + 2;        System.out.println(a.equals(c));        String d = "Hello";        String e = d + 2;        System.out.println(a.equals(e));                // 修改當前對象的數值        final StringBuffer tempbuffer = new StringBuffer("Hello, world!");        tempbuffer.append("This is final string!");        //        tempbuffer = new StringBuffer();// 無法重新引用新的資料    }}

 

聯繫我們

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