开发者

Static method returning inner class

I really don't understand why the getMyClass2 method below cannot be static, why 开发者_Go百科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();
    }
}


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();
    }
}


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜