请看下面的代码。代码 运行 没问题。输出是 [10,11]。行 final A a = new A(); 是什么意思?
Please look at the following code. Code is running fine. output is [10,11]. What is the meaning of line final A a = new A();
请看下面的代码:
public class Test
{
public static void main(String[] s)
{
final A a = new A(); // What is the meaning of this line ?
System.out.println(a.count);
a.count = 11;
System.out.println(a.count);
}
}
class A
{
int count = 10;
}
final A a = new A();行的含义是什么?
该行创建了 class A
的实例并将其分配给变量 a
。 final
表示无法重新分配变量。
所以当你不重新分配变量时你可以使用final
。例如,以下代码引发编译错误:
final A a = new A();
a = new A(); // reassignment causes error
一旦您使用 final
关键字声明并初始化了一个变量(无论它是原始类型还是引用类型),您将永远无法重新初始化它。这意味着在这个声明之后 -
final A a = new A();
您永远不能将 a
分配给这样的新引用 -
a = new A(); //another instance/object of `A` is created
但是如果你声明了一个no-final
变量anotherA
,那么你可以重新分配它 -
A anotherA = new A(); //声明和初始化
另一个 A = 新 A(); // 将 anotherA
重新分配给 A
类型的新 instance/object
final
关键字还强制您在变量声明时对其进行初始化。如果你尝试写这样的东西 -
final A a ; //only declare not initialized
然后会出现编译错误
请看下面的代码:
public class Test
{
public static void main(String[] s)
{
final A a = new A(); // What is the meaning of this line ?
System.out.println(a.count);
a.count = 11;
System.out.println(a.count);
}
}
class A
{
int count = 10;
}
final A a = new A();行的含义是什么?
该行创建了 class A
的实例并将其分配给变量 a
。 final
表示无法重新分配变量。
所以当你不重新分配变量时你可以使用final
。例如,以下代码引发编译错误:
final A a = new A();
a = new A(); // reassignment causes error
一旦您使用 final
关键字声明并初始化了一个变量(无论它是原始类型还是引用类型),您将永远无法重新初始化它。这意味着在这个声明之后 -
final A a = new A();
您永远不能将 a
分配给这样的新引用 -
a = new A(); //another instance/object of `A` is created
但是如果你声明了一个no-final
变量anotherA
,那么你可以重新分配它 -
A anotherA = new A(); //声明和初始化
另一个 A = 新 A(); // 将 anotherA
重新分配给 A
final
关键字还强制您在变量声明时对其进行初始化。如果你尝试写这样的东西 -
final A a ; //only declare not initialized
然后会出现编译错误