class
Inner class reference
With this example we are going to demonstrate how to make an inner class reference. In short, to make an inner class reference we have followed the above steps:
- We have created a class
InnerClassRef
, that contains an inner classC
and another inner classD
. - Class
C
has a methodvalue()
that returns an int value. - Class
D
has a methodreadLabel()
that returns a String value. - Class
InnerClassRef
has two methods,to(String s)
that returns aD
, andcont()
that returns aC
. It also has a methodboat(String dest)
that creates a newC
and a newD
instance, usingcont()
andto(String s)
methods. - We create a new instance of
InnerClassRef
and call itsboat(String s)
method with a given String. - Then we define the references to the inner classes of
InnerClassRef
usingcont()
andto(String s)
methods ofInnerClassRef
.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; public class InnerClassRef { public static void main(String[] args) { InnerClassRef inner1 = new InnerClassRef(); inner1.boat("Athens"); InnerClassRef inner2 = new InnerClassRef(); // Defining references to inner classes: InnerClassRef.C c = inner2.cont(); InnerClassRef.D d = inner2.to("Thessaloniki"); } class C { private int i = 11; public int value() { return i; } } class D { private String str; D(String whereTo) { str = whereTo; } String readLabel() { return str; } } public D to(String s) { return new D(s); } public C cont() { return new C(); } public void boat(String dest) { C c = cont(); D d = to(dest); System.out.println(d.readLabel()); } }
Output:
Athens
This was an example of how to make an inner class reference in Java.