How to create inner class objects in Java?

In Java, to create an object for a class we use new keyword. The new keyword creates an object for a class and initializes the object by calling its constructor. It is a strait forward thing to create an object for a class. But if we have another class within the class, then how can we create an instance of inner class?

This article explains the way we can create an instance of inner class.

First of all we can use the following statement to create an instance of a class:

ClassName variableName = new ClassName();

ClassName is the name of the class whose instance we want to create. variableName is the name of the variable where we store the instance of the Class. ClassName() is the constructor of the Class. If you don’t have the default constructor for your class, you can use any of the available constructors of the class to create instance of the class.

But things will different, if you want to create an instance for an inner classes. Inner classes are always bound with the outer classes. You can’t create an instance of an inner class without referring outer class.

If an inner class is non-static, you must use outer class’s object to create an inner class object. Following is the statement to create an inner class object.

OuterClassName outerobject = new OuterClassName();

InnerClassName innerobject = outerobject.new InnerClassName();

Observe that the innerobject is assigned with the instance of an inner class by using outer object to create an instance for inner class. So, you must create an outer object in-order to create an instance for a non-static inner class.

If your inner class is a static inner class, you can directly create an instance for inner class without creating an instance for outer class. But you must specify the outer class name. Following is the statement to create an instance for static inner class:

StaticInnerClassName innerclassobject = new OuterClassName.StaticInnerClassName();

Observe that to create an instance for static inner class, you need to use only the outer class name. But you need outer class object to create an instance for non-static inner class.

See the complete example below:

// — Outer class

public class Outer
{
// — Constructor
Outer()
{
System.out.println(“Outer Class Constructor”);
}
// — Inner class
class Inner
{
// — Constructor
Inner()
{
System.out.println(“Inner Class Constructor”);
}
}
// — Another inner class but it is static
static class StaticInner
{
StaticInner()
{
System.out.println(“Static Inner Constructor”);
}
}
// — main Method
public static void main(String[] args)
{
Outer outer = new Outer();
Inner inner = outer.new Inner();
StaticInner statinner = new Outer.StaticInner();
}
}

Leave a Reply