Final Keyword In Java

Introduction

final keyword can be used along with variables, methods and classes.

  • variable
  • method
  • class

Mnemonic

  • A final class cannot be extended by any other class
  • A final variable cannot be reassigned to another value
  • A final method cannot be overridden

Variable

final variable

We cannot change the value of a final variable once it is initialized.

class Student{

    final int studentID = 123;
    public void setID(){
        studentID = 456; //error
    }

    final static int numberOfStuent = 345; 
    static void setNumberOfStudent(){
        numberOfStuent = 789; //error
    }
}

blank final instance variable

  1. A final instance variable that is not initialized at the time of declaration is known as blank final variable.
  2. We must initialize the blank final instance variable in constructor of the class otherwise a compile-time error occurs.. (only initialize in constructor)
class Student{
    final int studentID;
    Student(){
        studentID = 123;
        studentID = 456; //error
    }
}

blank final class variable

A static final variable that is not initialized at the time of declaration is known as static blank final class variable. It can be initialized only in static block.

class Student{
    final static numberOfStuent;
    static{
        numberOfStudent = 789;
        numberOfStuednt = 999; //error
    }
}

final parameter

If you declare any parameter as final, you cannot change the value of it.

class Calculate(
    public static int increase(final int a){
        return ++a; //error
    }
)

Q) Whats the use of blank final variable?

Lets say we have a Student class which is having a field called Roll No. Since Roll No should not be changed once the student is registered, we can declare it as a final variable in a class but we cannot initialize roll no in advance for all the students(otherwise all students would be having same roll no)

class Student{
    final int ROLL_NO;
    Student(int ROLL_NO){
        this.ROLL_NO = ROLL_NO;
    }
}

Method

final method

A final method cannot be overridden.

The Counter is good example:

public class Counter{
    private int counter = 0;
    public final int count(){
        return counter++;
    }
    public final int reset(){
        return (counter = 0);
    }
}

If the public final int count() method is not final,we can do something like this:

Counter c = new Counter(){
    public int count(){
        super.count();
        return super.count();
    }
}
c.count();// not count2

Or something like this:

Counter c = new Counter(){
    public int count(){
        int lastCount = 0;
        for(int i = super.count(); --i >= 0;){
            lastCount = super.count();
        }
        return lastCount;
    }
}
c.count() // Now double count

Q) Is final method inherited?

Yes, final method is inherited but you cannot override.


Class

final class

Final class is complete in nature and can not be subclassed or inherited. Several classes in Java ar e final e.g. String, Integer and other wrapper classes.

Benefits of final keyword in Java

  1. Final keyword improves performance.
  2. Final variable are safe to share in multi-threading environment without additional synchronisation overhead.
  3. Fianl keyword allows JVM to optimised method, variable or class.

Reference

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子胜卤,更是在濱河造成了極大的恐慌浸间,老刑警劉巖妄辩,帶你破解...
    沈念sama閱讀 218,941評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件逢倍,死亡現(xiàn)場(chǎng)離奇詭異怔鳖,居然都是意外死亡摹菠,警方通過查閱死者的電腦和手機(jī)盒卸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來次氨,“玉大人蔽介,你說我怎么就攤上這事≡阈瑁” “怎么了屉佳?”我有些...
    開封第一講書人閱讀 165,345評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)洲押。 經(jīng)常有香客問我武花,道長(zhǎng),這世上最難降的妖魔是什么杈帐? 我笑而不...
    開封第一講書人閱讀 58,851評(píng)論 1 295
  • 正文 為了忘掉前任体箕,我火速辦了婚禮,結(jié)果婚禮上挑童,老公的妹妹穿的比我還像新娘累铅。我一直安慰自己,他們只是感情好站叼,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評(píng)論 6 392
  • 文/花漫 我一把揭開白布娃兽。 她就那樣靜靜地躺著,像睡著了一般尽楔。 火紅的嫁衣襯著肌膚如雪投储。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評(píng)論 1 305
  • 那天阔馋,我揣著相機(jī)與錄音玛荞,去河邊找鬼。 笑死呕寝,一個(gè)胖子當(dāng)著我的面吹牛勋眯,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,414評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼客蹋,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼塞蹭!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起嚼酝,我...
    開封第一講書人閱讀 39,319評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤浮还,失蹤者是張志新(化名)和其女友劉穎竟坛,沒想到半個(gè)月后闽巩,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡担汤,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年涎跨,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片崭歧。...
    茶點(diǎn)故事閱讀 40,096評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡隅很,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出率碾,到底是詐尸還是另有隱情叔营,我是刑警寧澤,帶...
    沈念sama閱讀 35,789評(píng)論 5 346
  • 正文 年R本政府宣布所宰,位于F島的核電站绒尊,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏仔粥。R本人自食惡果不足惜婴谱,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望躯泰。 院中可真熱鬧谭羔,春花似錦、人聲如沸麦向。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)诵竭。三九已至话告,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間秀撇,已是汗流浹背超棺。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評(píng)論 1 271
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留呵燕,地道東北人棠绘。 一個(gè)月前我還...
    沈念sama閱讀 48,308評(píng)論 3 372
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親氧苍。 傳聞我的和親對(duì)象是個(gè)殘疾皇子夜矗,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容