permaculture playing cards*
The moose likes Java in General and the fly likes Non static inner classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Non static inner classes" Watch "Non static inner classes" New topic
Author

Non static inner classes

santosh ks
Greenhorn

Joined: Dec 10, 2000
Posts: 2
How does this code work??
...
Outer o = null;
Outer.Inner = o.new Inner();
....

where Inner is a non static inner class of Outer.
Any ideas??
Preethi Suryam
Ranch Hand

Joined: Nov 17, 2000
Posts: 92
Hi Santosh!
The code which u gave does not work,b'coz outer can't be null.It gives a NullPointerException.check it out.
Preethi.
santosh ks
Greenhorn

Joined: Dec 10, 2000
Posts: 2
No it does work.
Try compiling and running this code.
I thought it shouldnt work but it does.
import java.util.*;
public class Sample4
{
public static void main(String[] args)
{
Outer o = null;
Outer.Inner in = o.new Inner();
}
}
class Outer
{
class Inner
{
{
System.out.println("Inner");
}
}
}
Rob Acraman
Ranch Hand

Joined: Dec 03, 2000
Posts: 89
Interesting one.
Taking the example a bit further:
<CODE>
import java.util.*;
public class Sample4
{
public static void main(String[] args)
{
Outer.Inner in = ((Outer)null).new Inner();
in.somejunk();
}
}
class Outer
{
int i;
class Inner
{
void somejunk()
{
System.out.println("Inner" +i);
}
}
}
</CODE>
This generates the NullPointerException at the println.
So, it appears the Inner class has a pointer to it's outer-class, and as long as that's given then it's happy (even if it's null).
Once created, all references to the outer class are implemented by pointer references, hence the NullPointer when we try to use them.
Anybody know where this is documented? (already tried the JLS).
Rob Acraman
Ranch Hand

Joined: Dec 03, 2000
Posts: 89
Scratch that last question (above).
Since there can be multiple instances of inner classes referring to the same parent object, of course it's the only sensible approach that each instance refers to the one enclosing outer object.
So, it's just a bug that the JVM doesn't check for null when creating the inner class (If it's not a bug, then it's a totally useless "feature" that should never be used).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Non static inner classes
 
Similar Threads
access inner class method
non-static inner class
Outer class instance
non-static inner class
static inner class?