File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Method-Local Inner Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Method-Local Inner Class " Watch "Method-Local Inner Class " New topic
Author

Method-Local Inner Class

Tarun Oohri
Ranch Hand

Joined: Feb 20, 2013
Posts: 176
In SCJP book , page number 672 .. Its written ..A local class declared in a static method has access to only static method of the enclosing class, since there is no associated instance of the enclosing class. If inner class is in a static method then there is no " this " .So an inner class in a static method is subject to have same restrictions as the static method. In other words no access to instance variables .
Following is the code in which "this " is working, where it should not because the inner class is in the static method.
Himai Minh
Ranch Hand

Joined: Jul 29, 2012
Posts: 775
The "this.f", refers to 8 in A.
Static method car can be accessed without using any instance of B.
Within car method scope, you can use A's instance to call any method inside A. Any change in B won't affect car. So, it is fine to use this.f to refer to the instance
variable of inner class A.

If you change your code like this:
Tarun Oohri
Ranch Hand

Joined: Feb 20, 2013
Posts: 176
Himai Minh wrote:The "this.f", refers to 8 in A.
Static method car can be accessed without using any instance of B.
Within car method scope, you can use A's instance to call any method inside A. Any change in B won't affect car. So, it is fine to use this.f to refer to the instance
variable of inner class A.


Thanks Himai, What you said is all right but my query was that why is it said that ( If inner class is in a static method then there is no " this " ) ...I could not understand the meaning of this line.
Himai Minh
Ranch Hand

Joined: Jul 29, 2012
Posts: 775
If you have a static inner class, then don't use this to refer to the enclosing class. Just like the case that don't use any "this" in static context.
Static members can be called without the instance of the class created. Before the instance of the class is created, don't use this to refer to it.

Tarun Oohri
Ranch Hand

Joined: Feb 20, 2013
Posts: 176
Himai Minh wrote:If you have a static inner class, then don't use this to refer to the enclosing class. Just like the case that don't use any "this" in static context.
Static members can be called without the instance of the class created. Before the instance of the class is created, don't use this to refer to it.



Thanks
 
Consider Paul's rocket mass heater.
 
subject: Method-Local Inner Class