Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static method returning inner class

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();
    }
}
like image 871
AOO Avatar asked Oct 30 '10 13:10

AOO


People also ask

Can we have static method in inner class?

Unlike top-level classes, Inner classes can be Static. Non-static nested classes are also known as Inner classes. An instance of an inner class cannot be created without an instance of the outer class.

Can you return in a static method?

it is a static method (static), it does not return any result (return type is void), and. it has a parameter of type array of strings (see Unit 7).

Can we declare inner class as static in Java?

Java static nested classA static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data members and methods. It can be accessed by outer class name.

How do you access a static inner class from another class?

They are accessed using the enclosing class name. For example, to create an object for the static nested class, use this syntax: OuterClass. StaticNestedClass nestedObject = new OuterClass.


2 Answers

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();
    }
}
like image 85
Gaim Avatar answered Nov 15 '22 13:11

Gaim


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.

like image 38
Flexo Avatar answered Nov 15 '22 14:11

Flexo