class
Reference to an inner class
This is an example of how to make a reference to an inner class. In order to make a reference to an inner class we have created a class with inner classes, as described in the steps below:
- We have created a class,
InnerClass1that has an int field and a methodint value()that returns an int field. - We have also created a class,
InnerClass2that has a String field, and a constructor that initializes its String field to a given String. It has a methodString readLabel()that returns the String field of the class. - Both classes are inner classes of
ReferenceInnerClass. - The class has a method
InnerClass2 to(String s)that returns a newInnerClass2object initialized with the given String field. - It also has a method
InnerClass1 cont()that returns a newInnerClass1object initialized by its default constructor. - Another method of
ReferenceInnerClassisvoid ship(String dest), where it callscont()method to get a newInnerClsas1object and thento(String s)to get a newInnerClass2object and prints the the field ofInnerClass2using itsreadLabel()method. - We create a new instance of
ReferenceInnerClass, and call itsship(String dest)method with a given String. - Then we create a new
ReferenceInnerClassobject, and follow the same steps asship(String dest)method, but calling thecont()andto(String s)methods of the inner classes.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
public class ReferenceInnerClass {
class InnerClass1 {
private int i = 11;
public int value() {
return i;
}
}
class InnerClass2 {
private String destination;
InnerClass2(String where) {
destination = where;
}
String readLabel() {
return destination;
}
}
public InnerClass2 to(String s) {
return new InnerClass2(s);
}
public InnerClass1 cont() {
return new InnerClass1();
}
public void ship(String dest) {
InnerClass1 c = cont();
InnerClass2 d = to(dest);
System.out.println(d.readLabel());
}
public static void main(String[] args) {
ReferenceInnerClass p = new ReferenceInnerClass();
p.ship("Athens");
ReferenceInnerClass q = new ReferenceInnerClass();
// Defining references to inner classes:
ReferenceInnerClass.InnerClass1 c = q.cont();
ReferenceInnerClass.InnerClass2 d = q.to("Thessaloniki");
}
}
This was an example of how to make a reference to an inner class in Java.
