In Java, the static
keyword typically flags a method or field as existing not once per instance of a class, but once ever. A class exists once anyway so in effect, all classes are "static" in this way and all objects are instances of classes.
static
does have a meaning for inner classes, which is entirely different: Usually an inner class instance can access the members of an outer class instance that it's tied to, but if the inner class is static
, it does not have such a reference and can be instantiated without an instance of the outer class. Maybe you saw that someplace, then tried to use it on a top-level class, where it isn't meaningful.
Or maybe you saw it in other languages like C#, whose syntax is an awful lot like Java's.
(One time I couldn't figure out why an outer class instance wasn't being garbage-collected -- it was because I was keeping a reference to one of its inner class instances elsewhere, and the inner class was not static
and so had a reference to the outer class instance. So by default, I make inner classes static
now.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…