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 class C and another inner class D.
  • Class C has a method value() that returns an int value.
  • Class D has a method readLabel() that returns a String value.
  • Class InnerClassRef has two methods, to(String s) that returns a D, and cont() that returns a C. It also has a method boat(String dest) that creates a new C and a new D instance, using cont() and to(String s) methods.
  • We create a new instance of InnerClassRef and call its boat(String s) method with a given String.
  • Then we define the references to the inner classes of InnerClassRef using cont() and to(String s) methods of InnerClassRef.

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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button