Difference between final and effectively final

后端 未结 14 3021
孤独总比滥情好
孤独总比滥情好 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:11

    However, starting in Java SE 8, a local class can access local variables and parameters of the >enclosing block that are final or effectively final.

    This didn't start on Java 8, I use this since long time. This code used (before java 8) to be legal:

    String str = ""; //<-- not accesible from anonymous classes implementation
    final String strFin = ""; //<-- accesible 
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
             String ann = str; // <---- error, must be final (IDE's gives the hint);
             String ann = strFin; // <---- legal;
             String str = "legal statement on java 7,"
                    +"Java 8 doesn't allow this, it thinks that I'm trying to use the str declared before the anonymous impl."; 
             //we are forced to use another name than str
        }
    );
    

提交回复
热议问题