java - a nonstatic field inside a static class

juztcode :

It's my first time coming across such pattern of code, it might be fairly familiar to advanced gurus out there:

public static class Myclass{
    public static class myChildClass{
        public int a =1;   //this doesn't give an error although I expected it should be declared static
    }
}  

I can't instantiate the static inner class and I can't access the variable int a outside the class, so does this variable become private to the class? Why does java allow this instead of complaining it be declared static?

Andy Turner :

I can't instantiate the static inner class

Of course you can:

Myclass.myChildclass m = new Myclass.myChildclass();

and I can't access the variable int a outside the class

Yes you can:

System.out.println(m.a);

so does this variable become private to the class?

No, because it's not private.

Why does java allow this instead of complaining it be declared static?

I think you misunderstand what a static class is: it's merely a nested class without an implicit reference to an instance of the enclosing class that created it. There is no requirement for its members to be static.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=400753&siteId=1