Re: Inner classes
I was playing around with inner classes and was
hopping someone could explain the following. Given:
import java.lang.reflect.*;
public class NestedScope {
private int num = 17;
public static void main ( String [] args ) {
NestedScope outer = new NestedScope();
outer.demo();
}
private void demo () {
Inner inner = new Inner();
inner.showNum();
}
private class Inner {
private void showNum () {
System.out.println( num ); // Displays 17
}
}
}
This works fine when compiled and run. But, I was cleaning
it up when I was done and noticed that javac had created
an extra class file:
C:\Temp>del *.class
C:\Temp>javac NestedScope.java
C:\Temp>dir *.class
Volume in drive C has no label.
Volume Serial Number is XXXX-XXXX
Directory of C:\Temp
08/30/2008 02:28 PM 184 NestedScope$1.class
08/30/2008 02:28 PM 756 NestedScope$Inner.class
08/30/2008 02:28 PM 671 NestedScope.class
3 File(s) 1,611 bytes
0 Dir(s) 3,213,533,184 bytes free
C:\Temp>javap NestedScope$1
Compiled from "NestedScope.java"
class NestedScope$1 extends java.lang.Object{
}
C:\Temp>del NestedScope$1.class
C:\Temp>java NestedScope
17
C:\Temp>javac -version
javac 1.6.0_07
C:\Temp>
"NestedScope$1" has no fields, constructors, or methods of it's own.
As the above shows it isn't used at all when the program is run.
Comment out the object creation (the whole body) of the
"demo" method, and then re-compiling, and the extra class doesn't
get generated.
It is true that there is no legal reason why a Java compiler can't
create temporary files but you expect them to be deleted when
the compiler finishes.
The class file naming scheme was recently codified into the language
definition, so there can be conflicts with "real" anonymous classes.
To check that out I added this to the main method:
new Object() {public void foo(){System.out.println("foo");}}.foo();
Which produced this result:
C:\Temp>del *.class
C:\Temp>javac NestedScope.java
C:\Temp>dir *.class
Volume in drive C has no label.
Volume Serial Number is 549D-754B
Directory of C:\Temp
08/30/2008 02:42 PM 501 NestedScope$1.class
08/30/2008 02:42 PM 756 NestedScope$Inner.class
08/30/2008 02:42 PM 706 NestedScope.class
3 File(s) 1,963 bytes
0 Dir(s) 3,205,283,840 bytes free
C:\Temp>java NestedScope
17
foo
C:\Temp>
As you can see the pointless NestedScope$1.class was not generated
at all (I expected NestedScope$2.class) in this case!
What am I missing? I bet it is something obvious. Or is this
some sort of "bug"?
-Wayne