class
Inner class instance example
In this example we shall show you how to call an inner classe’s instance in a class. To call an inner class instance in a class, we must first create an instance of the outer class, and then create an instance of the inner class, as described in the example:
- We have created a class,
InnerClassInstance
that has two inner classes,InnerClass1
andInnerClass2
. InnerClass1
has an int field initialized to a value, and a methodint value()
that returns its int field.InnerClass2
has a String field, a constructor where it initializes its String field to the given String, and a methodString readLabel()
that returns its String field.- We create a new instance of
InnerClassInstance
. - Then we create a new instance of each one of the inner classes, using the
InnerClassInstance
object and its inner classe’s constructors,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; public class InnerClassInstance { class InnerClass1 { private int i = 11; public int value() { return i; } } class InnerClass2 { private String dest; InnerClass2(String whereTo) { dest = whereTo; } String readLabel() { return dest; } } public static void main(String[] args) { InnerClassInstance p = new InnerClassInstance(); // Must use instance of outer class // to create an instances of the inner class: InnerClassInstance.InnerClass1 c = p.new InnerClass1(); InnerClassInstance.InnerClass2 d = p.new InnerClass2("Greece"); } }
This was an example of how to call an inner classe’s instance in a class in Java.