When is it appropriate to use blank final variables?

前端 未结 9 1407
野趣味
野趣味 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:20

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

提交回复
热议问题