Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Instantiating Static Inner classes with new Outer().new Inner()  RSS feed

Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If this has been discussed before please direct me to the post. Thanks.
When I try instantiating a static Inner class object using method #3 below, the Vm complains and gave me the following error... (note this happens during runtime only, it compiled without problems)
It just seems odd to me that #3 doesn't work because it's just the same as #1 except #1 provides a handler for the outer object. I know I'm trying to confuse myself because #2 would do the work just fine but I'm trying to learn inner classes as much as I can.
My question is whether #1 is legal at all even though the compiler doesn't complain.

Ken Lai

< !-- begin VM message-->
C:\forte4j\javacode>java Experiment
Exception in thread "main" java.lang.VerifyError: (class: Experiment,
method: ma
in signature: ([Ljava/lang/String V) Expecting to find unitialized object
on st
< !-- end message-->
< !-- begin code-->
class Experiment
{ String classType = "Experiment" ;

public static void main(String[] args)
//#1 will work
Outer outerObj = new Outer() ;
Outer.Inner InnerObj1 = Inner() ;
//#2 will work too
Outer.Inner InnerObj2 = new Outer.Inner() ;
//#3 won't work!!
Outer.Inner InnerObj3 = new Outer().new Inner() ;

class Outer
System.out.println("Creating Outer object") ;

static class Inner
System.out.println("Creating Inner object") ;

}//class Inner
}//class Outer
< !-- end code-->
Posts: 3226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you refer to a <CODE>static</CODE> member of a class (even if it's another class), you don't have to use the class name as in
If you could have an object of class Math (which you can't but the example is till valid), and that object would be denoted by the variable "myMathObject", then you could refer to Math.PI as myMathObject.PI and it would be the PI of the Math class that would be referenced.
I don't know why the designers of Java allowed this but it's legal.
That should explain your results. Number 3 should not even compile because one doesn't need and <CODE>Outer</CODE> instance.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!