When is it appropriate to use blank final variables?

前端 未结 9 1390
野趣味
野趣味 2020-12-16 00:24

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 reaso

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 01:00

    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.

提交回复
热议问题