Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Non static inner classes

 
santosh ks
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic