java 什么时候适合使用空白最终变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11345747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When is it appropriate to use blank final variables?
提问by Rob Volgman
I was looking at another questionabout final variables and noticed that you can declare final variables without initializing them (a blank finalvariable). Is there a reason it is desirable to do this, and when is it advantageous?
我正在查看有关最终变量的另一个问题,并注意到您可以在不初始化它们的情况下声明最终变量(一个空白的最终变量)。是否有理由这样做是可取的,什么时候是有利的?
回答by assylias
This is useful to create immutable objects:
这对于创建不可变对象很有用:
public class Bla {
private final Color color;
public Bla(Color c) {this.color = c};
}
Bla is immutable (once created, it can't change because color is final). But you can still create various Blas by constructing them with various colors.
Bla 是不可变的(一旦创建,就不能更改,因为颜色是最终的)。但是您仍然可以通过用各种颜色构建它们来创建各种 Blas。
See also this questionfor example.
例如,另请参见此问题。
EDIT
编辑
Maybe worth adding that a "blank final" has a very specific meaning in Java, which seems to have created some confusion in the comments - cf the Java Language Specification 4.12.4:
也许值得补充的是,“空白最终”在 Java 中具有非常具体的含义,这似乎在评论中造成了一些混乱 - 参见Java 语言规范 4.12.4:
A blank final is a final variable whose declaration lacks an initializer.
空白 final 是声明缺少初始化程序的 final 变量。
You then must assign that blank final variable in a constructor.
然后,您必须在构造函数中分配该空白最终变量。
回答by Damian Leszczyński - Vash
The final property of class must have a value assigned before object is created. So the last point where you can assign value to them is constructor.
类的最终属性必须在创建对象之前赋值。因此,您可以为它们赋值的最后一点是构造函数。
This is used often for immutable objects.
这通常用于不可变对象。
public class Foo {
private final Bar bar;
public Foo(Bar bar) {
this.bar = bar;
}
public Bar getBar() {
return new Bar(bar);
}
}
回答by John Kane
You can do this when you do not known what the value will be prior to the instrumentation of a Object, it just needs to have a value assigned in its constructor.
当您在检测对象之前不知道值是什么时,您可以执行此操作,它只需要在其构造函数中分配一个值。
This is how you make immutable objectsand it is used in the builder pattern.
这就是您制作不可变对象的方式,它在构建器模式中使用。
class Builder{
final BuilderContext context;
private Builder(BuilderContext context){
this.context=context;
}
public static Builder New(){
return new Builder(new BuilderContext());
}
回答by Rainer Schwarze
Blank final variables must be assigned "somewhere" in the constructor. A rather constructed example:
必须在构造函数中的“某处”分配空白最终变量。一个相当构造的例子:
public class Test {
final int sign;
public Test(String upDown) {
if (upDown.equals("up")) {
sign = +1;
} else {
sign = -1;
}
}
}
回答by Gustav Barkefors
One case could be when you have a field which you want to declare final, but whose assignment may throw an exception and you want to be able to take action if that happens:
一种情况可能是当您有一个要声明为 final 的字段,但其赋值可能会引发异常并且您希望能够在发生这种情况时采取行动:
class A {
final URLConnection conn;
A(String url) {
try {
this.conn = new URL(url).openConnection();
} catch (IOException | MalformedURLException e) {
// Maybe this isn't fatal, so just handle the Exception
// here and move on happily
}
}
}
回答by user3653789
Use a blank final variable inside a method to show that all code paths which use the variable assign that variable exactly once (or throw an exception). Java compilers will guarantee that a blank final variable is assigned before it is used.
在方法中使用一个空白的 final 变量来显示所有使用该变量的代码路径只分配该变量一次(或抛出异常)。Java 编译器将保证在使用之前分配一个空白的 final 变量。
Example code inside some method:
一些方法中的示例代码:
final Foo foo;
if (condition1()) {
foo = makeFoo(1);
} else if (condition2()) {
throw new BarException();
} else {
foo = makeFoo(-1);
}
...
blahBlahBlah(foo);
Using blank final variables tells the next reader of the code that the compiler guarantees that someone assigned foo before calling blahBlahBlah(foo).
使用空白最终变量告诉代码的下一个读者,编译器保证有人在调用 blahBlahBlah(foo) 之前分配了 foo。
The question asks about "blank final variables". Discussion of "blank final fields" is a different discussion, and interesting in its own right.
该问题询问“空白最终变量”。对“空白最终字段”的讨论是一个不同的讨论,它本身就很有趣。
回答by Dustin
I find them very useful for methods that derive a state. It provides a clean execution path and makes sure the state variable is assigned once and only once. For example:
我发现它们对于导出状态的方法非常有用。它提供了一个干净的执行路径并确保状态变量被分配一次且仅一次。例如:
public boolean isEdible() {
final boolean edible;
if (vegetable) {
edible = true;
} else if (animal) {
if (vegetarian) {
edible = false;
} else {
edible = true;
}
}
System.out.println("Is edible: " + edible);
return edible;
}
回答by Pshemo
noticed that you can declare
final
variables without initializing them
注意到你可以在
final
不初始化变量的情况下声明变量
You have to initialize it later (for example in the constructor) so it wont stay empty.
您必须稍后对其进行初始化(例如在构造函数中),因此它不会保持为空。
回答by marty bourque
From Wikipedia
来自维基百科
The blank final, which was introduced in Java 1.1, is a final variable whose declaration lacks an initializer. A blank final can only be assigned once and must be unassigned when an assignment occurs. In order to do this, a Java compiler runs a flow analysis to ensure that, for every assignment to a blank final variable, the variable is definitely unassigned before the assignment; otherwise a compile-time error occurs.
在 Java 1.1 中引入的空白 final 是一个 final 变量,它的声明缺少初始化程序。空白期末只能分配一次,并且在分配发生时必须取消分配。为了做到这一点,Java 编译器运行了一个流程分析,以确保对于空的 final 变量的每次赋值,该变量在赋值之前肯定是未赋值的;否则会发生编译时错误。
In general, a Java compiler will ensure that the blank final is not used until it is assigned a value and that once assigned a value, the now final variable cannot be reassigned another value.
通常,Java 编译器将确保空白 final 在被赋值之前不会被使用,并且一旦赋值,现在的 final 变量不能重新赋值。