During the two days of program writing, I encountered a problem: the parameter must be in final state (final); otherwise, the program reports an error! After a long time of thinking, I still couldn't figure out why I went online for half a day. Finally, I got an expert in a QQ group and found some related information. Although I still don't know much about it, I found the direction. Write it down now!
Test code:
Code:
- Import java. AWT. image;
- Public class test
- {
- // Public void outputa (image) // error code
- Public void outputa (final image)
- {
- New testb (){
- Public void output ()
- {
- System. Out. println (image. getwidth (null ));
- }
- };
- }
- }
- Class testb
- {
- Public void outputb (image)
- {
- Int width = image. getwidth (null );
- }
- }
As shown above, if you change the code of Line 1 to line 2 (that is, comment 6th rows and uncomment 5th rows), the program will prompt at Line 11: cannot refer to a non-final variable image inside an inner class defined in a different method.
As a result, this parameter becomes the final parameter. In this regard, I found a bit of information: Java allows us to set parameters to final attributes by making appropriate declarations in the parameter list. This means that within this method, we cannot change the object that the parameter points ).
A netizen told me:
【
Thinking in Java (the only correct statement ):
If you define an anonymous internal class and want it to use an object determined externally, the compiler will require its parameter reference to be final.
Note:
1. anonymous internal classes must be partial internal classes (internal classes defined in a method), because in Java, the statements must be written in the method, the anonymous internal class is actually a special statement;
2. the externally given object is all external objects: the form parameters, local variables, basic types, or custom types of external methods.
]
I downloaded a thinkinjava.pdf file from the Internet, but I couldn't find the above content after it was opened. Oh, let it go for now. Stay tuned for future research!