Static method returning inner class

2019-06-16 05:23发布

问题:

I really don't understand why the getMyClass2 method below cannot be static, why isn't it valid Java code?

public class MyClass
{
    private class MyClass2
    {
        public String s1 = "";
        public String s2 = "";
    }

    private MyClass2 myClass2;

    private static MyClass2 getMyClass2()
    {
        MyClass2 myClass2 = new MyClass2();
        return myClass2;
    }

    public MyClass()
    {
        myClass2 = getMyClass2();
    }
}

回答1:

You have to say that the inner class is static because non-static is bound to the instance so it cannot be returned from static method

public class MyClass
{
    private static class MyClass2
    {
        public String s1 = "";
        public String s2 = "";
    }

    private MyClass2 myClass2;

    private static MyClass2 getMyClass2()
    {
        MyClass2 myClass2 = new MyClass2();
        return myClass2;
    }

    public MyClass()
    {
        myClass2 = getMyClass2();
    }
}


回答2:

The (non static) inner class instances are always associated with an instance of the class they are contained within. The static method will be called without reference to a specific instance of MyClass, therefore if it created an instance of MyClass2 there would be no instance of MyClass for it to be associated to.



回答3:

Yes,

because 99% of the time you don't want them static ;D

A static "nested" class is nothing more than a "top level" class that is defined inside of another class. If the static class MyClass2 in the example above would be public, you simply could say new MyClass.MyClass2(); In case of a normal "inner class" you would hav to say that to an object, not to the class MyClass: MyClass some = new MyClass() and then something like new some.MyClass2() (I forgot the exact syntax).

Regards