在這篇文章中,我們將看看 java 的不同的 Final 關鍵字。它是java語言中使用的關鍵字,用來限制其他類別或變數的使用或修改。使用此關鍵字,可以告訴解釋器不允許將來對該變數或方法進行任何修改,並將其視為常數。它可以用於以下 3 種場景:-
廣告 該類別中的熱門課程 財務建模與估值 - 專業化 | 51 課程系列 | 30 次模擬測驗開始您的免費軟體開發課程
網頁開發、程式語言、軟體測試及其他
根據良好的編碼實踐,始終建議使用大寫字母聲明這些關鍵字。
此關鍵字可以透過以下 3 種方式使用:-
java中的變數可以宣告為變數來限制其值的任何變更。可以透過以下三種方式中的任何一種來聲明-
文法:
final int VAR1=21;//final variable final int VAR2; //blank final variable static final double DUMMY= 45.504;//final static variable static final double PK;//blank final static variable
最終字串產生器 sb= new StringBuilder(“LetsLearn”);
用final關鍵字宣告的方法稱為final方法。 Final方法不能被子類別重寫,這表示子類別方法不能更改父類別中存在的final方法的定義。當我們希望所有子類別都必須遵循父類別中定義的方法的實作時,我們必須將該方法宣告為final。
文法:
final int my1(){ //method defination }
final 關鍵字也可以與類別一起使用,使其成為最終類,這意味著特定類別不能被任何其他類別擴展或繼承。
文法:
final class myClass{ /member variables and member functions. }
final 關鍵字有助於限制繼承過程中類別、成員或變數的重寫。
將變數宣告為final意味著限制繼承類別中對該變數值的任何變更。 Final 變數只能初始化一次,且必須按原樣使用;因此,必須初始化一個最終變數。它主要與 static 一起使用來創建常數類別變數。
例如:
final int a =0;
我們也可以將引用變數宣告為final;在這種情況下,一個引用變數不能引用不同的物件。但在java中,物件的內部狀態是可以改變的;最終參考變數指的是這一點。因此我們可以更改參考變數的值。這與使用最終數組相同,如下所示:-
代碼:
class MyClass { public static void main(String args[]) { final int myarr[] = {1, 2, 3, 4, 5}; for (int q = 0; q < myarr.length; q++) { myarr [q] = myarr [q]*10; System.out.println(myarr [q]); } } }
輸出:
說明
這裡,陣列a1引用同一個物件;只有該物件的值正在改變,因為我們都知道陣列變數只包含儲存陣列元素的記憶體位置的起始位址。
同樣,如果我們嘗試使用相同的數組變數 a1 來引用不同的數組,那麼編譯器將拋出錯誤。因此,這裡使用 word-final 數組意味著可以對數組成員進行任何更改,但不允許該變數引用任何其他物件。
要記住的事情
初始化最終變數對於防止編譯時錯誤是必要的。 C++ const 變數和這些final 變數之間的差異在於const 變數不需要初始化。初始化final變數有3種方法-
Thus, the final keyword is used for those variables that need not change their value during the program’s execution. All the final variables created inside a method or block must be initialized there itself. Such type of variables is known as local final variables.
Explanation
In the below example, a variable I has been declared within the main function and initialised is considered a final local variable.
Code:
class myClass { public static void main(String args[]) { // local final variable final int i; i = 20; System.out.println(i); } }
Output:
A method declared as final can not be overridden in any of the subclasses, thus called a final method. The method needs to be declared as final if we require that the child classes follow the class’s same implementation.
Note- Final methods don’t need to be declared in the initial stage of inheritance(base class ). The method can be declared final in any subclass that we want further subclasses to follow the same definition.Code:
class A{ void myMethod(){ //method definition } } class B extends A{ final void myMethod(){ //overrides the method in parent class //runs successfully } } class C extends B{ void myMethod(){ //will throw error } }
Classes declared as final can not be inherited by any other classes. Mentioning a final keyword before the class name tells the compiler that this class’s definition can only be used as they are. No other classes can add their specifications to this definition or reuse its code. If one attempts to extend the final class, an error is thrown by the compiler indicating that this class is not meant to be extended. One can use final keywords in java in any for below 2 purposes:-
final class myParentClass { // member variables and member functions } // illegal extend. class myChildClass extends parentClass { // <--COMPILE-ERROR—> Can't subclass A }
Note-
Below is the Different Example of Final Keyword in Java are:
In the below example, different variables are initialized using various methods. For example- the SECOND variable is initialized using a constructor, whereas THIRD is initialized using an initializer.
Code:
class myClass { final int FIRST = 5; // a blank final variable final int SECOND; // another blank final variable final int THIRD; FIRST =10; //illegal attempt to change the value of final variable // a final static variable PI // direct initialize static final double MINVALUE = 3.141592653589793; // a blank final static variable static final double MAXRANGE; { THIRD = 25; // initializer block } static{ MAXRANGE = 200.3; } public myClass() { SECOND = -1;//needs to be initialised in every constructor } }
Output:
In the below example, abstract class myShape declares final methods getWidth and get eight those need not be overridden by the inherited classes. It also declares one abstract function whose implementation is mandatory in the subsequent classes. Thus the only the definition of an abstract function is implemented in a first child class and a second child class.
Code:
abstract class myShape { private double width; private double height; public myShape(double width, double height) { this.width = width; this.height = height; } public final double getWidth() //override not allowed { return width; } public final double getHeight() //override not allowed { return height; } abstract double getArea(); //needs to be defined in the child class } class firstChildClass extends myShape { public firstChildClass(double width, double height) { super(width, height); } final double getArea() { return this.getHeight() * this.getWidth(); } } class secondChildClass extends myShape { public secondChildClass(double side) { super(side, side); } final double getArea() { return this.getHeight() * this.getWidth(); } } public class myClass { public static void main(String[] args) { myShape s1 = new firstChildClass(10, 20); myShape s2 = new secondChildClass(10); System.out.println("width of s1 : "+ s1.getWidth()); System.out.println("height of s1 : "+ s1.getHeight()); System.out.println("width of s2 : "+ s2.getWidth()); System.out.println("height of s2 : "+ s2.getHeight()); System.out.println("area of s1 : "+ s1.getArea()); System.out.println("area of s2 : "+ s2.getArea()); } }
Output:
In the below program, we are using a final class Solid that defines a method to calculate the volume of a shape using its dimensions, but displaying the volume of a box is done using the inherited class’s printVol function. Shape As Solid is a final class; thus, class Shape will not be allowed to extend(or inherit) it. Thus, it uses Shape’s object to calculate the volume of any of Shape by just passing the arguments to the functions.
Code:
final class Solid { public double getVol(double length, double width, double height) { return length * width * height; } } class Shape { private float length; private float width; private float height; Shape(float length, float width, float height) { this.length = length; this.width = width; this.height = height; } public void printVol(Solid bObj) { double volume = bObj.getVol(this.length, this.width, this.height); System.out.println("Volume of the Shape: " + volume); } } public class myClass { public static void main(String[] args) { Solid bObj = new Solid(); Shape obj = new Shape(5, 4, 3); obj.printVol(bObj); } }
Output:
The final keyword is used to prevent the classes, variables, and methods to be overridden by its child classes. It can also be used to make classes immutable that is restricting the change in the value of their objects. The final keyword check is always checked at the compile time only. It is a great utility to prevent the reuse of the defined variables, logic, and classes.
以上是Java 中的 Final 關鍵字的詳細內容。更多資訊請關注PHP中文網其他相關文章!