0

I found that we can not use a non-final variable inside the method of an inner Class, But when I did an experiment myself I got the different result

There are few Answers on StackOverflow describing the reason Why Java inner classes require "final" outer instance variables? , I understood the concept, And tried it myself with two classes in IntelliJ

Driver Class

public class Driver{
  public static void main(String[] args) {
  String outsideVar = "anything";
  InterfaceClassTest object1 = new InterfaceClassTest() {
        @Override
        public void InterfaceFunction() {
                System.out.println(outsideVar);
         }
    };
  object1.InterfaceFunction();  
};}

InterfaceClassTest Class

 public interface InterfaceClassTest {
  public abstract void InterfaceFunction();
  }

I expected I would get an error for the above code, But it worked fine, So how come I can use outsideVar in inner class's method

nikhil123
  • 48
  • 1
  • 10
  • 1
    The variable is effectively final, IE the compiler can detect that no changes are made to it. This changed in java 8(? might have been earlier) – David Zimmerman Jan 24 '19 at 17:32
  • @DavidZimmerman oh, Yes that must be the reason, I have updated version of JAVA, Thanks! – nikhil123 Jan 24 '19 at 17:34

0 Answers0