为什么在Java中不能将类声明为静态?


当前回答

In addition to how Java defines static inner classes, there is another definition of static classes as per the C# world [1]. A static class is one that has only static methods (functions) and it is meant to support procedural programming. Such classes aren't really classes in that the user of the class is only interested in the helper functions and not in creating instances of the class. While static classes are supported in C#, no such direct support exists in Java. You can however use enums to mimic C# static classes in Java so that a user can never create instances of a given class (even using reflection) [2]:

public enum StaticClass2 {
    // Empty enum trick to avoid instance creation
    ; // this semi-colon is important

    public static boolean isEmpty(final String s) {
        return s == null || s.isEmpty();
    }
}

其他回答

默认情况下,顶级类是静态的。默认情况下,内部类是非静态的。您可以通过显式地将内部类标记为静态来更改它们的默认值。顶级类由于是顶级类,所以不能具有非静态语义,因为没有父类可以引用。因此,无法更改顶级类的默认值。

具有私有构造函数的类是静态的。

像这样声明你的类:

public class eOAuth {

    private eOAuth(){}

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

}

你可以在不初始化的情况下使用:

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

所以,我来晚了,但这是我的两种观点——哲学上补充科林·赫伯特的答案。

在高层次上,你的问题涉及对象和类型之间的区别。虽然有很多Car(对象),但只有一个Car类(类型)。将某些内容声明为静态意味着您在“类型”空间中操作。只有一个。顶级类关键字已经在“type”空间中定义了一个类型。因此,“公共静态类Car”是多余的。

我们在java中编写的所有代码都包含在一个类中。每当我们运行一个类时,JVM都会实例化一个对象。JVM可以创建许多对象,根据定义,静态意味着对所有对象都有相同的复制集。

所以,如果Java允许顶级类是静态的,无论何时你运行一个程序,它都会创建一个对象,并保持在相同的内存位置上重写。

如果你只是在每次运行时替换对象,那么创建它有什么意义呢?

这就是Java摆脱顶级类静态的原因。

可能有更具体的原因,但这对我来说更合乎逻辑。

唯一可以是静态的类是内部类。下面的代码工作得很好:

public class whatever {
    static class innerclass {
    }
}

静态内部类的意义在于它们没有外部类对象的引用。