本文翻译自:Why are you not able to declare a class as static in Java?
为什么你不能在Java中将类声明为静态?
#1楼
参考:https://stackoom.com/question/F2OH/为什么你不能在Java中将类声明为静态
#2楼
I think this is possible as easy as drink a glass of coffee!. 我认为这可以像喝一杯咖啡一样简单! Just take a look at this. 看看这个。 We do not use static keyword explicitly while defining class. 我们在定义类时不会显式使用static关键字。
public class StaticClass {
static private int me = 3;
public static void printHelloWorld() {
System.out.println("Hello World");
}
public static void main(String[] args) {
StaticClass.printHelloWorld();
System.out.println(StaticClass.me);
}
}
Is not that a definition of static class? 这不是静态类的定义吗? We just use a function binded to just a class. 我们只使用绑定到一个类的函数。 Be careful that in this case we can use another class in that nested. 请注意,在这种情况下,我们可以在嵌套中使用另一个类。 Look at this: 看这个:
class StaticClass1 {
public static int yum = 4;
static void printHowAreYou() {
System.out.println("How are you?");
}
}
public class StaticClass {
static int me = 3;
public static void printHelloWorld() {
System.out.println("Hello World");
StaticClass1.printHowAreYou();
System.out.println(StaticClass1.yum);
}
public static void main(String[] args) {
StaticClass.printHelloWorld();
System.out.println(StaticClass.me);
}
}
#3楼
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();
...
#4楼
One can look at PlatformUI
in Eclipse for a class with static methods and private constructor with itself being final. 可以在Eclipse中查看具有静态方法的类的PlatformUI
和私有构造函数,其本身是最终的。
public final class <class name>
{
//static constants
//static memebers
}
#5楼
如果使用静态类的好处不是实例化一个对象并使用一个方法,那么只需将该类声明为public,并将此方法声明为static。
#6楼
In addition to how Java defines static inner classes, there is another definition of static classes as per the C# world [1] . 除了Java如何定义静态内部类之外,还有另一种静态类的定义,根据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. 虽然C#支持静态类,但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] : 但是,您可以使用枚举来模拟Java中的C#静态类,以便用户永远不能创建给定类的实例(甚至使用反射) [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();
}
}