When is it appropriate to use blank final variable

2019-02-08 16:54发布

I was looking at another question about final variables and noticed that you can declare final variables without initializing them (a blank final variable). Is there a reason it is desirable to do this, and when is it advantageous?

标签: java final
9条回答
啃猪蹄的小仙女
2楼-- · 2019-02-08 17:29

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);
 } 
}

What wiki says about it

Defensive copying.

查看更多
老娘就宠你
3楼-- · 2019-02-08 17:30

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:

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
    }
  }
}
查看更多
Lonely孤独者°
4楼-- · 2019-02-08 17:31

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;
}
查看更多
▲ chillily
5楼-- · 2019-02-08 17:36

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;
        }
    }
}
查看更多
可以哭但决不认输i
6楼-- · 2019-02-08 17:47

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.

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).

The question asks about "blank final variables". Discussion of "blank final fields" is a different discussion, and interesting in its own right.

查看更多
Rolldiameter
7楼-- · 2019-02-08 17:47

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.

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.

查看更多
登录 后发表回答