NeoGeoSNK said:
I have two questions, why inner class can only access "final" argument
outside the inner class?
There is a distinction between member variables, local variables, and
formal parameter variables (though the last two are darned similar).
There is also a distinction between anonymous inner classes, named
inner classes, and static inner classes.
An anonymous inner class is defined inside a method, and has access to all
member variables of the enclosing class, final or not (which isn't your
question), and to all final variables and parameters of the method in which
it's declared (which is what you're asking about). The reason they have
to be final is because they're locally scoped and will disappear as
soon as the method returns, which would be very bad for the anonymous class
that tries to reference them later. The final modifier means it's safe for
the anonymous class to keep a copy of the value when it's created, as it's
guranteed not to change.
Named inner classes (those that are members of a class, not declared inside a
method) have no access to any method's parameters or variables at all, so
nothing needs to be declared final. It has access to member variables of the
enclosing class through an implicit OuterClassName.this reference.
Named static inner classes are exactly like top-level classes (which are
implicitly static). They have no access to any outside variables, except
through an explicit reference just like any other class would.
and why Java applet's init() method can't access any "final" fields?
public class AppletGui extends JApplet {
.........
final JTextField textvalue;
..........
public void init(){
..........
textvalue = new JTextField(25); //this will
encounter a compiled time error "the final field AppletGui.textvalue
can not be assigned
This is unrelated to your first question. Final member variables must be
assigned at class construction time (through an initializer in the
declaration, an initializer block, or inside a constructor. Any attempt to
assign to a final member after this is illegal. That's what final means - it
can't be assigned after construction.