Java中的最终变量
在Java中,我们可以在变量、方法和类中使用 final 关键字。当 final 关键字与原始数据类型(如 int、float 等)的变量一起使用时,变量的值不能更改。
示例 1: final 与原始数据类型的用法
Java
// Java Program to illustrate Use of Final Keyword
// With Primitive Datatypes
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
// Final primitive variable
final int i = 10;
i = 30;
// Error will be generated above
}
}
Java
// Java Program to illustrate Use of Final Keyword
// With Primitive Datatypes
// Class 1
class Helper {
int i = 10;
}
// Clss 2
// main class
class GFG {
// Main driver method
public static void main(String args[])
{
final Helper t1 = new Helper();
t1.i = 30; // Works
// Print statement for successful execution of
// Program
System.out.print("Successfully executed");
}
}
输出:
现在您一定想知道如果我们确实使用 final 关键字非原始变量会怎样,让我们在示例的帮助下探索与上面所做的相同的事情。
Note: Non-primitive variables are always references to objects in Java, the members of the referred object can be changed. final for non-primitive variables just means that they cannot be changed to refer to any other object.
示例 2: final 与原始数据类型的用法
Java
// Java Program to illustrate Use of Final Keyword
// With Primitive Datatypes
// Class 1
class Helper {
int i = 10;
}
// Clss 2
// main class
class GFG {
// Main driver method
public static void main(String args[])
{
final Helper t1 = new Helper();
t1.i = 30; // Works
// Print statement for successful execution of
// Program
System.out.print("Successfully executed");
}
}
输出
Successfully executed