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


当前回答

如上所述,一个类不能是静态的,除非它是另一个类的成员。

如果你想要设计一个“不能有多个实例”的类,你可能想要研究一下“单例”设计模式。

这里是初学者单例信息。

警告:

如果您正在考虑使用 单例模式,抵制与所有 你的可能。这是最简单的方法之一 设计模式来理解,可能 最受欢迎的,绝对是 大多数滥用。 (来源:JavaRanch,如上图所示)

其他回答

如上所述,一个类不能是静态的,除非它是另一个类的成员。

如果你想要设计一个“不能有多个实例”的类,你可能想要研究一下“单例”设计模式。

这里是初学者单例信息。

警告:

如果您正在考虑使用 单例模式,抵制与所有 你的可能。这是最简单的方法之一 设计模式来理解,可能 最受欢迎的,绝对是 大多数滥用。 (来源:JavaRanch,如上图所示)

当然可以,但只能是内部嵌套类。在这里,它意味着嵌套类的实例不需要外部类的封闭实例。

但是对于顶级类,语言设计者想不出任何有用的关键字,所以它是不允许的。

您可以通过声明一个没有实例的enum类型来创建一个实用程序类(它不能创建实例)。也就是说,你明确地声明没有实例。

public enum MyUtilities {;
   public static void myMethod();
}

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

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();
    }
}