class

Creating inner class example

This is an example of how to create an inner class. In short, to create an inner class we have performed the following steps:

  • We have created a class CreatingInner that contains two inner classes, Contents and Destination.
  • Contents class has a method value() and Destination class has a constructor using a String field and a method readLabel().
  • CreatingInner class has a method ship(String dest), that creates new instances of its inner classes.
  • We create a new instance of CreatingInner class, and call its ship(String dest) method to create new instances of the inner classes too.

Let’s take a look at the code snippet that follows: 

package com.javacodegeeks.snippets.core;

public class CreatingInner {

    public static void main(String[] args) {

  CreatingInner p = new CreatingInner();

  p.ship("Athens");
    }

    class Contents {


  private int i = 11;


  public int value() {


return i;

  }
    }

    class Destination {


  private String label;


  Destination(String whereTo) {


label = whereTo;

  }


  String readLabel() {


return label;

  }
    }

    // Using inner classes looks just like
    // using any other class, within Parcel1:
    public void ship(String dest) {

  Contents c = new Contents();

  Destination d = new Destination(dest);

  System.out.println(d.readLabel());
    }
}

  
This was an example of how to create an inner class in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron 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