Question

I am able to create instances of the static inner class without compilation error. What does this mean? How does java allow one to create objects for static class?.. Kindly help me with this.

public class StringMatrix {
    static class moves{
        int x;
        int y;
        moves(int x,int y){
            this.x=x;
            this.y = y;
        }
        static moves[] movements = {new moves(0,1),new moves(1,1),new moves(0,-1),new moves(1,0),new moves(-1,0),new moves(-1,-1),new moves(-1,1),new moves(1,-1)};
    }
}
Was it helpful?

Solution 2

Java is allow to create static inner class.

A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

You can access static nested classes are accessed using the enclosing class name: like

StringMatrix.moves

Why do we need static nested class?

static nested classes aren't really needed. However, you could make the argument that if two classes are only used together -- such as class A uses helper class B, and B is never used independently -- then a static nested class is the way to go. In other words, by making B just a regular old class, the programmer who stumbles across it may try to use it. If B were a static nested class, then it's more clear that it has a special use that relates to A.

OTHER TIPS

These are not called inner classes but "static nested classes". They are declared static within their outer class, which means that they can exist without an instantiation of the outer class. They are really just a normal class that is defined inside another class in order to make the code easier to read and better grouped.

For more information, see Java's documentation

When an inner class is static, its differences from a top-level class are very small: it uses its outer class in a way similar to a name space, and gets access to other static members of its outer class without having to specify the name of the class. In all other respects it is the same as a top-level class: in particular, it can be instantiated from a static context, the way that you do in your code example.

Non-static inner classes add an implicit reference to the instance of its outer class. This is what changes the rules of instantiation - now you need an instance of an outer class in order to instantiate an inner class.

It's really just a way to define two related classes together in one file. To instantiate your moves class you would do:

int x=1;
int y=1;
moves m = new StringMatrix.moves(x,y);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top