Class Outer.Inner
will be loaded the first time another class that refers to it as a variable type, method parameter type, method return type, superclass type, type parameter bound, or target type of an initializer or static method, or host class of a static variable reference is loaded. In your example, I would expect it never to be loaded.
Also,I wanted to know,how to create an instance of inner class in the above example?
As it is written, class Outer.Inner
is accessible only inside method Outer.method1()
, therefore it can be instantiated only within that method. There, you can just use new Inner()
. If you want it to be instantiable from elsewhere then move its declaration out of the method body:
class Outer
{
class Inner
{
}
void method1()
{
}
}
That's better form for a named inner class anyway. It will not change when or whether Outer.Inner
is loaded.
With that change, you can instantiate Outer.Inner
anywhere within a constructor or instance method of Outer
via the form new Inner()
. If, however, you want to instantiate one from a different class, or in a static method of class Outer
, then it's a bit trickier. The important thing to realize is that each instance of Outer.Inner
needs an associated instance of Outer
. This is determined from context when the instantiation is performed in an instance method of Outer
, but if it is performed without such a context then the syntax is:
public static void main(String args[])
{
Outer obj=new Outer();
Outer.Inner inner = obj.new Outer.Inner();
}