为什么在Java中不能将类声明为静态?
当前回答
所以,我来晚了,但这是我的两种观点——哲学上补充科林·赫伯特的答案。
在高层次上,你的问题涉及对象和类型之间的区别。虽然有很多Car(对象),但只有一个Car类(类型)。将某些内容声明为静态意味着您在“类型”空间中操作。只有一个。顶级类关键字已经在“type”空间中定义了一个类型。因此,“公共静态类Car”是多余的。
其他回答
所以,我来晚了,但这是我的两种观点——哲学上补充科林·赫伯特的答案。
在高层次上,你的问题涉及对象和类型之间的区别。虽然有很多Car(对象),但只有一个Car类(类型)。将某些内容声明为静态意味着您在“类型”空间中操作。只有一个。顶级类关键字已经在“type”空间中定义了一个类型。因此,“公共静态类Car”是多余的。
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();
...
您可以在Eclipse中的PlatformUI中查看带有静态方法和私有构造函数的类,该类本身是final的。
public final class <class name>
{
//static constants
//static memebers
}
您可以通过声明一个没有实例的enum类型来创建一个实用程序类(它不能创建实例)。也就是说,你明确地声明没有实例。
public enum MyUtilities {;
public static void myMethod();
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap