Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 279
barak manos Avatar asked Jun 06 '26 17:06

barak manos


1 Answers

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().

like image 69
Dawood ibn Kareem Avatar answered Jun 08 '26 07:06

Dawood ibn Kareem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!