views:

61

answers:

3

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();
    }
}
+5  A: 

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();
    }
}
Gaim
+1 for showing static inner class
awoodland
Is there a reason why inner classes are not static by default?
AOO
@AOO I don't think there's actually much use for them
awoodland
+2  A: 

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.

awoodland
They aren't always associated with the instance, only when they aren't static
Gaim
Thanks, clarified that in my text.
awoodland
@Gaim: inner classes are never static. They're to be called nested classes.
BalusC
@BalusC Okey, I am sorry for bad terminology.
Gaim
Thanks all, I learned from this question despite knowing the answer to what the OP asked :)
awoodland
A: 

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

Angel O'Sphere