barak manos
barak manos

Reputation: 30136

Return an instance of an inner class from a static method in Java

The following are user requirements which I cannot change:

  1. A class with a static interface (all methods are static).

  2. One specific method returns an ArrayList<String> object and a File object.

The following is my implementation of the above requirements:

  1. An inner class which contains an ArrayList<String> object and a File object.

  2. The specific method initializes an instance of the inner class and returns it at the end.

But I am unable to create an instance of the inner class without creating an instance of the outer class:

public class Outer
{
    public class Inner
    {
        ArrayList<String> strings;
        File              file;
    }

    public static Inner method()
    {
        Inner inner = new Outer().new Inner();
        ...
        return inner;
    }
}

Besides being "ugly", the new Outer().new Inner() feels pretty incorrect.

Is there a different approach that I can take in order to avoid having to instantiate the outer class?

Upvotes: 3

Views: 1519

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

If you make the inner class static (that is, you write public static class Inner) then you don't need an instance of the outer class; you can just write new Outer.Inner().

Upvotes: 6

Related Questions