Difference between final and effectively final

后端 未结 14 3015
孤独总比滥情好
孤独总比滥情好 2020-11-22 00:38

I\'m playing with lambdas in Java 8 and I came across warning local variables referenced from a lambda expression must be final or effectively final. I know tha

14条回答
  •  深忆病人
    2020-11-22 01:12

    final is a variable declare with key word final , example:

    final double pi = 3.14 ;
    

    it remains final through out the program.

    effectively final : any local variable or parameter that is assigned a value only once right now(or updated only once). It may not remain effectively final through out the program. so this means that effectively final variable might loose its effectively final property after immediately the time it gets assigned/updated at least one more assignment. example:

    class EffectivelyFinal {
    
        public static void main(String[] args) {
            calculate(124,53);
        }
    
        public static void calculate( int operand1, int operand2){   
         int rem = 0;  //   operand1, operand2 and rem are effectively final here
         rem = operand1%2  // rem lost its effectively final property here because it gets its second assignment 
                           // operand1, operand2 are still effectively final here 
            class operators{
    
                void setNum(){
                    operand1 =   operand2%2;  // operand1 lost its effectively final property here because it gets its second assignment
                }
    
                int add(){
                    return rem + operand2;  // does not compile because rem is not effectively final
                }
                int multiply(){
                    return rem * operand1;  // does not compile because both rem and operand1 are not effectively final
                }
            }   
       }    
    }
    

提交回复
热议问题