• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Non-Static Inner class w/in method

 
Paul Salerno
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Im trying to nail down the syntax for non-static inner classes within a method vs member non-static inner classes vs annonymous inner classes.
From two souces I have found:
1. non-static inner classes- have free access to all member variables & methods of enclosing outer class including private members; instantiated with a non-static method.
2. non-static inner classes w/in a method- can only access final local variables of method or final parameters passed to the method; they can't have static methods.
I'm a little confused as to why this is the case, and I would love to see short examples of each.
-------------------------------------------------
(this question is not so imperitave)
3. anonymous inner classes- don't have constructors & java invokes the super class constructor() implicitly; can use this or super
Therefore can anonymous inner classes have free access to the outer class member variables and methods?
-------------------------------------------------
I do not have any code example to post, so if anyone could provide a short example I would be greatly appreciative.
Thanks!
-Paul
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Paul,
Your first thesis is correct. However, your second should be reworded to be:
2. Same as above with the added restrictions that the class can not be declared static or access any method variable that is not declared final.
Why? Because any class that gets created inside a method might exist after the method is completed. From basic programming we know that when a method completes all local variables are destroyed and can no longer be used. Knowing that we can easily see why the class can not be static or use non-final local variables.
Number 3 is correct because it should say:
3. The same as number 1 except the class has no name and therefore no constructors.
To use a variable from the outer class you simply use the this construct. For example:

Regards,
Manfred.
 
Paul Salerno
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Manfred,
You wrote:
2. Same as above with the added restrictions that the class can not be declared static or access any method variable that is not declared final.
What about static inner classes aka top level nested classes. I want to be sure that these do not have free access to non static variables of outer class, only local variables declared final; instantiated w/ static method of enclosing class of which I have never seen. how is this one similar/ disimilar??
TIA
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic