The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
March 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Just show the supremacy of Outer class

Posted by Kishori Sharan on April 01, 2001 at 4:52 PM

Hi
You are right that Java creates a new anonymous class Outer$1 if you declare the constructor of static inner class as private. Here is the reason why it needs to create that extra class.
The Nested class's constructor has been declared private. So by general theory no other class can create an object of Nested class. However, an enclosing class can always create an object of enclosed class irrespective of the access modifier used with the construtor of inner class. This is allowed by Java and makes sense. If you cannot create an object of inner class then why would you create that class at all. However, to JVM this fact is not known. JVM won't allow you to create an object of a class whose constructor has been defined private. So JVM won't allow like:
Nested n = new Nested ( ) ;
if Nested class has a private constructor then JVM won't execute the above expression. However, in case of this expression appearing within Outer class, this has to be a valid expression for JVM. So Java compiler does some tweaking around with inner class code and call to inner class construtor. Conside the following piece of code.
class Outer {
static class Nested (
private Nested ( ) {
}
}
public static void main ( String[] args ) {
Nested n = new Nested ( ) ;
}
}

The main method code is not valid for JVM. So Java compiler creates an anonymous class within Outer class and also adds a new construtor to Nested class. Suppose the anonymous class defined is as
class Anony {
}
and the new construtor added to Nested class is
Nested ( Anony aa ) {
this() ;
}

Now Java compiler changes the piece of code in main method as
Nested n = new Nested ( null ) ;
Now you can see the JVM won't have any problem in calling Nested ( null ) construtor and at the same time Outer can create an object of Nested class despite its constructor being private. So the modified Outer class for Java comnpiler is
class Outer {
class Anony { // Leads to creation of Outer$1
}
static Nested {
private Nested ( ) { }
Nested ( Anony aa ) { this(); } // Added by Java Compiler
}
public static void main ( String[] args ) {
Nested n = new Nested ( null ) ; // Modified by Java Compiler
}
}
}

This is why Java Compiler creates a new class Outer$1.

Thanx
Kishori



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us