This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
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
posted
0
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
posted
0
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
posted
0
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
posted
0
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).