Why are you not able to declare a class as static in Java?

为什么你不能在Java中声明一个类是静态的?


Only nested classes can be static. By doing so you can use the nested class without having an instance of the outer class.

class OuterClass{
    public static class StaticNestedClass{
    }

    public class InnerClass{
    }

    public InnerClass getAnInnerClass(){
        return new InnerClass();
    }

    //This method doesn't work
    public static InnerClass getAnInnerClassStatically(){
        return new InnerClass();
    }
}

class OtherClass{
    //Use of a static nested class:
    private OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();

    //Doesn't work
    private OuterClass.InnerClass innerClass = new OuterClass.InnerClass();

    //Use of an inner class:
    private OuterClass outerclass= new OuterClass();
    private OuterClass.InnerClass innerClass2 = outerclass.getAnInnerClass();
    private OuterClass.InnerClass innerClass3 = outerclass.new InnerClass();
}

Sources :

  • Oracle tutorial on nested classes
  • On the same topic :

  • Java: Static vs non static inner class
  • Java inner class and static nested class

  • Class with private constructor is static.

    Declare your class like this:

    public class eOAuth {
    
        private eOAuth(){}
    
        public final static int    ECodeOauthInvalidGrant = 0x1;
        public final static int    ECodeOauthUnknown       = 0x10;
        public static GetSomeStuff(){}
    
    }
    

    and you can used without initialization:

    if (value == eOAuth.ECodeOauthInvalidGrant)
        eOAuth.GetSomeStuff();
    ...
    

    So, I'm coming late to the party, but here's my two cents - philosophically adding to Colin Hebert's answer.

    At a high level your question deals with the difference between objects and types. While there are many cars (objects), there is only one Car class (type). Declaring something as static means that you are operating in the "type" space. There is only one. The top-level class keyword already defines a type in the "type" space. As a result "public static class Car" is redundant.

    链接地址: http://www.djcxy.com/p/76128.html

    上一篇: 现在做什么?

    下一篇: 为什么你不能在Java中声明一个类是静态的?