java - Constants and inner classes -
static
variables in inner classes: inner class cannot containstatic
fields. cannot containstatic
members, because there problem assignstatic
member. inner class connected outer class. understand why not containstatic
member, inner class can containstatic
constant. why? specially treated? on special heap? still static member, constant, specially treated?it can contain: "final static int x", not "static int x".
i wonder why variables of method used in local class should
final
. mean:public void function1() { final int x; // value of x, used in class have final class { void function2() { //body of function } } }
the answer is: variable x id copied class a. cannot changed, because there appeared inconsistency. why architects of java did not create language variable x not copied? address of variable passed , variable x changed without inconsistency. can give me example , explain this?
or issue connected synchronization. both variables should same, if out of scope? 1 of variables not exits, synchronization?
edit: why works:
interface in { void f1(); } class { int variable = 3; in g() { return new in() { @override public void f1() { variable = 6; system.out.println(variable); } }; } } public static void main(string[] args) { in in1; { a = new a(); in1 = a.g(); } in1.f1(); //class not exists more, field 'variable' changed, despite not exist }
why there no synchronization problem?
to answer first question:
personally, don't see yet why doesn't accept non-final static members in inner classes. however, can tell happens on compile time. when declare static final
primitive member, can compiled code uses member. however, when try create static final object o = new object();
, cannot know on compile time o
pointing at. , gives same compiler error if create static int
(non-final) in inner-class.
to answer second question, here why:
x
local variable, pushed onto stack. when use reference x
in inner class, have problems. because inner class going live longer scope of function. function ends, x
goes out of scope , gets removed stack. so, right now, inner class still has reference variable doesn't exist anymore. so, little trick implemented in compiler: if declare x
final
compiler knows won't change, there no point of keeping reference it. allows compiler copy x
instance of inner class new member. thus, x
copied heap. compare invalid reference stack if not mark final (which doesn't compile of course, because compiler protects of making mistake).
Comments
Post a Comment