首頁 > Java > java教程 > Java 中的 Final 關鍵字

Java 中的 Final 關鍵字

WBOY
發布: 2024-08-30 15:22:49
原創
662 人瀏覽過

在這篇文章中,我們將看看 java 的不同的 Final 關鍵字。它是java語言中使用的關鍵字,用來限制其他類別或變數的使用或修改。使用此關鍵字,可以告訴解釋器不允許將來對該變數或方法進行任何修改,並將其視為常數。它可以用於以下 3 種場景:-

廣告 該類別中的熱門課程 財務建模與估值 - 專業化 | 51 課程系列 | 30 次模擬測驗

開始您的免費軟體開發課程

網頁開發、程式語言、軟體測試及其他

  1. 變數:將變數宣告為final會限制其修改以引用任何其他值或參考。
  2. 方法: 將方法宣告為 Final 會限制子類別中該方法的重寫。
  3. 類別:將類別宣告為final可以防止繼承該類別。

根據良好的編碼實踐,始終建議使用大寫字母聲明這些關鍵字。

Java 中 Final 關鍵字的語法

此關鍵字可以透過以下 3 種方式使用:-

1.變數

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”);

2.方法

用final關鍵字宣告的方法稱為final方法。 Final方法不能被子類別重寫,這表示子類別方法不能更改父類別中存在的final方法的定義。當我們希望所有子類別都必須遵循父類別中定義的方法的實作時,我們必須將該方法宣告為final。

文法:

final int my1(){
//method defination
}
登入後複製

3.課程

final 關鍵字也可以與類別一起使用,使其成為最終類,這意味著特定類別不能被任何其他類別擴展或繼承。

文法:

final class myClass{
/member variables and member functions.
}
登入後複製

Final 關鍵字在 Java 中如何運作?

final 關鍵字有助於限制繼承過程中類別、成員或變數的重寫。

1.最終變數

將變數宣告為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]);
}
}
}
登入後複製

輸出:

Java 中的 Final 關鍵字

說明

這裡,陣列a1引用同一個物件;只有該物件的值正在改變,因為我們都知道陣列變數只包含儲存陣列元素的記憶體位置的起始位址。

同樣,如果我們嘗試使用相同的數組變數 a1 來引用不同的數組,那麼編譯器將拋出錯誤。因此,這裡使用 word-final 數組意味著可以對數組成員進行任何更改,但不允許該變數引用任何其他物件。

要記住的事情

初始化最終變數對於防止編譯時錯誤是必要的。 C++ const 變數和這些final 變數之間的差異在於const 變數不需要初始化。初始化final變數有3種方法-

  • Initialize at the time of declaration itself: We can easily declare a final variable at the time of declaring it. In case it is not initialized, then that variable is considered a blank final variable, and either of the next 2 ways can help us initialize a blank final variable.
  • Using instance-initializer block: Inside this block or the constructor, a blank final variable can be easily initialized. While using a constructor to initialize, always remember to initialize the particular variable in all the available constructors.
  • Static Block: One can also use a static block to initialize the blank final variable. Static block is always triggered once for each class; thus, the variable value whose values are not meant to be altered can easily be initialized using this block.

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:

Java 中的 Final 關鍵字

2. Final Methods

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
}
}
登入後複製

3. Final Classes

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:-

  1. The first is to prevent the inheritance of that class. E.g., all the Wrapper classes present java.lang package is final classes; therefore, we cannot extend them in our classes but can use it by declaring their objects. Any attempt to access those classes will result in an error by the compiler.
final class myParentClass
{
// member variables and member functions
}
// illegal extend.
class myChildClass extends parentClass
{
// <--COMPILE-ERROR—> Can't subclass A
}
登入後複製
  1. The second use of final with classes is when one needs to create an immutable class, i.e. once the class’s object is created, we cannot change its content like the predefined String class. The class must be declared as final to make it immutable.

Note-

  • If a class is declared as final, then its member variables and member functions are also considered final by the compiler.
  • A class cannot be declared abstract where it depends on the child classes to complete its definition and final, which prevents the inheritance itself.

Examples of Final Keywords in Java

Below is the Different Example of Final Keyword in Java are:

1. Using Final Variable

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:

Java 中的 Final 關鍵字

2. Using Final Methods

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:

Java 中的 Final 關鍵字

3. Using Final Classes

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: 

Java 中的 Final 關鍵字

Conclusion

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中文網其他相關文章!

相關標籤:
來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板