Monday, 5 August 2013

Java - Creating an instance of a inner class

Note: In order to make it work, the inner class must be visible for the external class. This means it cannot be private or be protected and belong to another package.

The nested class is a specific code technic which allow the user to have a class inside another one. This is very useful to hide the class from others. But insted of having private inner class, the inner class could be public or protected, allowing other classes use it.

In this case, the syntax of the java code is a bit special. For example, if we have a class called ExampleClass which contains a inner class called InnerClass, where the inner class has an attrabute of int called id, and the ExampleClass has two attributes: name as String and innerClass as InnerClass. Well, something like the follow one:

public class ExampleClass {

protected class InnerClass {
private int id;

public InnerClass(int id) {
super();
this.id = id;
}
                // Getter and setters

@Override
public String toString() {
return "InnerClass [id=" + id + "]";
}

}
private InnerClass innerClass;

private String name;

public ExampleClass() {}

        // Getter and setters
@Override
public String toString() {
return "ExampleClass [innerClass=" + innerClass + ", name=" + name
+ "]";
}
}

We can call the method new of an instance of the class ExampleClass to create an instance of InnerClass.

ExampleClass exampleClass = new ExampleClass();
exampleClass.setInnerClass(exampleClass.new InnerClass(0));
exampleClass.setName("ExampleClass name");
System.out.println(exampleClass);

InnerClass innerClass = exampleClass.new InnerClass(1);
exampleClass.setInnerClass(innerClass);
System.out.println(exampleClass);

The result could be something like this:

ExampleClass [innerClass=InnerClass [id=0], name=ExampleClass name]
ExampleClass [innerClass=InnerClass [id=1], name=ExampleClass name]

Source:

Source code:

No comments:

Post a Comment