• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method-Local Inner Class

 
Tarun Oohri
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1255
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1255
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic