gpt4 book ai didi

java - 这个 "s"实际上是最终的吗?

转载 作者:搜寻专家 更新时间:2023-10-31 20:00:49 24 4
gpt4 key购买 nike

这是一些示例代码(假设是 Java 8)。

while (true){
Socket s = serverSocket.accept();
// some code here ... we don't assign anything to s again here ...
}

s 在循环中是有效的 final 吗?

最佳答案

假设 s 没有在其声明之后被赋值,那么是的,根据 JLS, Section 4.12.4s 是“有效最终的” ,它定义了它,在你的情况下:

Certain variables that are not declared final are instead considered effectively final:

  • A local variable whose declarator has an initializer (§14.4.2) is effectively final if all of the following are true:

    • It is not declared final.

    • It never occurs as the left hand side in an assignment expression (§15.26). (Note that the local variable declarator containing the initializer is not an assignment expression.)

    • It never occurs as the operand of a prefix or postfix increment or decrement operator (§15.14, §15.15).

  • A local variable whose declarator lacks an initializer is effectively final if all of the following are true:

    • It is not declared final.

    • Whenever it occurs as the left hand side in an assignment expression, it is definitely unassigned and not definitely assigned before the assignment; that is, it is definitely unassigned and not definitely assigned after the right hand side of the assignment expression (§16 (Definite Assignment)).

    • It never occurs as the operand of a prefix or postfix increment or decrement operator.

您只能在声明时分配 s,作为一个对象,它不能作为递增或递减运算符的操作数,因此它实际上是最终的。

它还说明了一个变量在另一种情况下可以是有效的final,如果它在声明时没有被赋值,只要它只被赋值一次,它肯定在声明之前没有被赋值,它肯定在声明之后被赋值。

此外,在该部分的末尾,它指出:

If a variable is effectively final, adding the final modifier to its declaration will not introduce any compile-time errors. Conversely, a local variable or parameter that is declared final in a valid program becomes effectively final if the final modifier is removed.

您应该能够显式地使其成为 final 而不会导致编译器错误。如果是这样,它实际上是最终的。

关于java - 这个 "s"实际上是最终的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35351389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com