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]

Community
  • 1
  • 1
chepseskaf
  • 664
  • 2
  • 12
  • 41

3 Answers3

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.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • 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 Oct 04 '13 at 13:03
  • @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`. – OldCurmudgeon Oct 04 '13 at 13:19
  • 1
    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 Oct 04 '13 at 14:13
  • @Pigelvy - For demonstration mostly. I do not recall ever needing to do it this way in real life. – OldCurmudgeon Oct 04 '13 at 14:24
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.

Vincent van der Weele
  • 12,927
  • 1
  • 33
  • 61
  • You seem to understand the question but your answer is all about the technic itself, not the pertinence/usage of this technic. – Pigelvy Oct 04 '13 at 14:08
  • 1
    @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... – Vincent van der Weele Oct 04 '13 at 14:53
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();
    }
}
Heaven42
  • 329
  • 1
  • 13