首页 >Java >java教程 >Java 中的 Final 关键字

Java 中的 Final 关键字

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB原创
2024-08-30 15:22:49697浏览

在这篇文章中,我们将看看 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn