1

I've seen this sample code from Oracle Website about Java ?

public class Parent { class InnerClass { void methodInFirstLevel(int x) { // some code } } public static void main(String... args) { Parent parent = new Parent(); Parent.InnerClass inner = parent.new InnerClass(); } } 
  • What is the purpose of the construct parent.new InnerClass()?
  • What kind of classes would be suited to such construction?

The title may be misleading: I understand everything about this construct.

I just don't understand where and when to use this Java feature.

I found another syntax to do the same: Java: Non-static nested classes and instance.super()

There are lot's of references about this structure, but nothing about the application.

[References]

8
  • One good use is a static inner class named Builder for the Builder design pattern... Commented Oct 4, 2013 at 12:01
  • The official Java tutorial covers them: docs.oracle.com/javase/tutorial/java/javaOO/nested.html Commented Oct 4, 2013 at 12:01
  • 4
    Not specific for Java 8, has existed probably since the first Java version Commented Oct 4, 2013 at 12:01
  • 2
    @MarkRotteveel: Oh, yes indeed. There's a "Why use nested classes" section in the page. Not sure how an answer could explain what several pages of the tutorial can't. Commented Oct 4, 2013 at 12:04
  • 1
    @JBNizet Seems to be down the middle in version 1.1 :) en.wikipedia.org/wiki/Inner_class#Programming_languages Commented Oct 4, 2013 at 12:04

3 Answers 3

2

What is the purpose of parent.new InnerClass()?

This is for demonstration - using this mechanism to construct an inner class is rare. Normally inner classes are created only by the outer class when it is just created with new InnerClass() as usual.

What kind of classes would be suited to such construction?

Look at Map.Entry<K,V> for a classic example. Here you can see an inner class called Entry that should be created by all classes that implement Map.

Sign up to request clarification or add additional context in comments.

4 Comments

The structure provided in the sample require to create an instance of Parent before create an instance of InnerClass. I do not understand the link with Map.Entry ?
@chepseskaf - for non-static inner classes, each one has a connection to its parent so that it can access the parent's fields and methods so a parent must already exist for each child to attach to. It makes sense to enclosed the Entry class in the Map class because each type of Map is likely to have have different kinds of Entry.
I'm next to @chepseskaf and we fully undestand what an inner non-static class is and its relation to its parent. What we can not figure out is why would somebody instanciate a Parent and then need to instanciate an InnerClass from the Parent instance. This is very different from the Map.Entry example. What use case would need such a technic?
@Pigelvy - For demonstration mostly. I do not recall ever needing to do it this way in real life.
1

I see many answers here explaining the use of inner classes, but as far as I can see, the question is about the specific construct parent.new InnerClass().

The reason for that syntax is very simple: an instance of an inner class must belong to an instance of the surrounding class. But since main is a static method, there is no surrounding Parent object. Therefore, you must explicitly specify that object.

public static void main(String[] args) { // this results in an error: // no enclosing instance of type Parent is available InnterClass inner = new InnerClass(); // this works because you specify the surrounding object Parent parent = new Parent(); InnerClass inner = parent.new InnerClass(); } 

I'm searching for a use of this construct in the standard packages, but so far I haven't found an example.

2 Comments

You seem to understand the question but your answer is all about the technic itself, not the pertinence/usage of this technic.
@Pigelvy you are right. The reason is that I don't see a use for this syntax. Every example I come up with can be solved easier without it...
0

Inner classes nest within other classes. A normal class is a direct member of a package, a top-level class. Inner classes, which became available with Java 1.1, come in four flavors:

  • Static member classes
  • Member classes
  • Local classes
  • Anonymous classes

the most important feature of the inner class is that it allows you to turn things into objects that you normally wouldn't turn into objects. That allows your code to be even more object-oriented than it would be without inner classes.

public class DataStructure { // create an array private final static int SIZE = 15; private int[] arrayOfInts = new int[SIZE]; public DataStructure() { // fill the array with ascending integer values for (int i = 0; i < SIZE; i++) { arrayOfInts[i] = i; } } public void printEven() { // print out values of even indices of the array InnerEvenIterator iterator = this.new InnerEvenIterator(); while (iterator.hasNext()) { System.out.println(iterator.getNext() + " "); } } // inner class implements the Iterator pattern private class InnerEvenIterator { // start stepping through the array from the beginning private int next = 0; public boolean hasNext() { // check if a current element is the last in the array return (next <= SIZE - 1); } public int getNext() { // record a value of an even index of the array int retValue = arrayOfInts[next]; //get the next even element next += 2; return retValue; } } public static void main(String s[]) { // fill the array with integer values and print out only // values of even indices DataStructure ds = new DataStructure(); ds.printEven(); } } 

3 Comments

This sentence "allows you to turn things into objects that you normally wouldn't turn into objects" doesn't make a lot of sense to me.
Please see my edit, with an example illustrating perfectly this sentence
I don't see how this illustrates that sentence; one could wonder though if creating an iterator here is needed and wanted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.