Java knowledge: Variables must be declared as final outside the inner class if they are used in the inner class

  • Any local variables used but not declared in the inner class must be assigned explicitly before the body of the inner class
  • All local variables used in the methods of Java anonymous inner classes must be defined as final
  • In the JVM, the internal class does not directly call the parameters of the method, but the internal class backs up the passed parameters to its own internal through its own constructor, and the internal method calls are actually their own attributes rather than the external class methods. parameter

For example:

class A{
    
    
	final string a = “aabbcc”;
	class B{
    
    
		print(a);
	}
}

The function print() of the inner class B in class A calls the parameter a defined in A. At this time, if final is not added, an error will occur. Because when the inner class is compiled, a separate .class file of the inner class is generated, which is not in the same class file as the outer class

Note:
If the variable is not modified by final, the internal class can change the value of the variable when it is used, which violates the principle of data consistency. Because from the programmer’s point of view, they are the same thing. If the programmer changes the value of the parameter in the internal class during program design, but finds that the value has not been changed when the external call is made, it will make people It is very difficult to understand and accept. In order to avoid this embarrassing problem, the compiler designer sets the parameters that can be used by the internal class to be final to avoid this inexplicable error.

Guess you like

Origin blog.csdn.net/sinat_34241861/article/details/115185546