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
CreatingInnerthat contains two inner classes,ContentsandDestination. - Contents class has a method
value()andDestinationclass has a constructor using a String field and a methodreadLabel(). CreatingInnerclass has a methodship(String dest), that creates new instances of its inner classes.- We create a new instance of
CreatingInnerclass, and call itsship(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.
