Hi, friends, i m having doubt about innerclass which declared inside method.
As we know that such a innerclass can access only final local variables of the method.
Also I know that all final variables accessed by Inner Class are implicitly added as its member variables to the Innerclass by Java Compiler.So it can be accessed after method completes....You can check this in the following code you are still getting x 's value by myAA 's referece.
Now after removing the comment at Class AA.... where i m confused is in Class AA also having member x with value 123 now innnerClass accessing the method variable x .so according to member hiding principle the output should be 90 but with surprise it comes....123
So can any body answer my query ?
[EMAIL]rutvij(at)elitecore.com[/EMAIL] [ June 23, 2005: Message edited by: Barry Gaunt ]
Hi , Thats because even when u extend a class only methods can be inherited and not variables.Try the same by changing the access modifier of the variable X to private in both the classes and see the result.It would be as expected by you.Hope this should explain you.
sorry for the prev reply. I saw the values the other way.Ok.... the reason is tat when a class gets loaded the instance variables are loaded first when compared with the methd local variables.
Here in our case,the value of x which is inside the METHOD getref() is not at all loaded ,but when u explicitly instantiate the myAA inner class which extends the class AA the value of x=123 is getting loaded and that is being returned by getMyVal() function.
Put the variable x=90 inside the inner class and see the difference in the result. Always the order of instantiation is 1.static variables/blocks 2.constructors 3.instance variables (initialised before the constructor is initialised fully) 4.methods (on calling).
I think the method`s final variables can be used by any method local inner class, but cannot be referred using a class instance. Consider the following code,
The above code gives a compilation error, saying that it cannot resolve symbol x in my.x. If I remove the comment from line 1, the code compiles correctly and gives 190 as the output. This means that the method`s final variables can be used inside a method local inner class, but can`t be treated as a instance variable of the inner class. I am saying this looking at the above behaviour of the code. Please correct me if I am wrong, any more explanation is welcome!!
What I said was "the method`s final variables can be used by any method local inner class, but cannot be referred using a class instance." is true anyway because it is one of the local class' variable access rules. ( only the local class inside that method can access the local final variables defined in there, not any method, though )