为什么不能在 Java 中将类声明为静态类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3584113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why are you not able to declare a class as static in Java?
提问by Mariselvam
Why are you not able to declare a class as static in Java?
为什么不能在 Java 中将类声明为静态类?
采纳答案by Colin Hebert
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 :
来源:
On the same topic :
在同一主题上:
回答by Andreas Dolk
public class Outer {
public static class Inner {}
}
... it can be declared static - as long as it is a member class.
...它可以声明为静态 - 只要它是一个成员类。
From the JLS:
来自 JLS:
Member classes may be static, in which case they have no access to the instance variables of the surrounding class; or they may be inner classes (§8.1.3).
成员类可能是静态的,在这种情况下,它们无法访问周围类的实例变量;或者它们可能是内部类(第 8.1.3 节)。
and here:
和这里:
The static keyword may modify the declaration of a member type C within the body of a non-inner class T. Its effect is to declare that C is not an inner class.Just as a static method of T has no current instance of T in its body, C also has no current instance of T, nor does it have any lexically enclosing instances.
static 关键字可以在非内部类 T 的主体内修改成员类型 C 的声明。它的作用是声明 C 不是内部类。正如 T 的静态方法在其主体中没有 T 的当前实例一样,C 也没有 T 的当前实例,也没有任何词法封闭实例。
A static keyword wouldn't make any sense for a top level class, just because a top level class has no enclosing type.
static 关键字对于顶级类没有任何意义,因为顶级类没有封闭类型。
回答by Michael Borgwardt
Sure they can, but only innernested classes. There, it means that instances of the nested class do not require an enclosing instance of the outer class.
当然可以,但只能是内部嵌套类。这意味着嵌套类的实例不需要外部类的封闭实例。
But for top-level classes, the language designers couldn't think of anything useful to do with the keyword, so it's not allowed.
但是对于顶级类,语言设计者想不出用关键字做任何有用的事情,所以它是不允许的。
回答by S.Jones
As explained above, a Class cannot be static unless it's a member of another Class.
如上所述,一个类不能是静态的,除非它是另一个类的成员。
If you're looking to design a class "of which there cannot be multiple instances", you may want to look into the "Singleton" design pattern.
如果您想设计一个“不能有多个实例”的类,您可能需要查看“单例”设计模式。
Beginner Singleton info here.
初学者单身信息在这里。
Caveat:
警告:
If you are thinking of using the singleton pattern, resist with all your might. It is one of the easiest DesignPatterns to understand, probably the most popular, and definitely the most abused. (source: JavaRanch as linked above)
如果您正在考虑使用单例模式,请竭尽全力抵制。它是最容易理解的 DesignPatterns 之一,可能是最流行的,也绝对是最被滥用的。 (来源:上面链接的 JavaRanch)
回答by Peter Lawrey
You can create a utility class (which cannot have instances created) by declaring an enum type with no instances. i.e. you are specificly declaring that there are no instances.
您可以通过声明一个没有实例的枚举类型来创建一个实用程序类(不能创建实例)。即您特别声明没有实例。
public enum MyUtilities {;
public static void myMethod();
}
回答by Erfankam
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);
}
}
回答by Sergey Vakulenko
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();
...
回答by user175881
One can look at PlatformUI
in Eclipse for a class with static methods and private constructor with itself being final.
可以PlatformUI
在 Eclipse 中查看具有静态方法和私有构造函数的类,其本身是最终的。
public final class <class name>
{
//static constants
//static memebers
}
回答by eeadev
if the benefit of using a static-class was not to instantiate an object and using a method then just declare the class as public and this method as static.
如果使用静态类的好处不是实例化对象和使用方法,那么只需将类声明为公共类,将此方法声明为静态。
回答by shams
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]:
除了 Java 如何定义静态内部类之外,根据 C# 世界[1],还有另一个静态类定义。静态类是只有静态方法(函数)的类,它旨在支持过程编程。这样的类并不是真正的类,因为类的用户只对辅助函数感兴趣,而不对创建类的实例感兴趣。虽然 C# 支持静态类,但 Java 中不存在这种直接支持。但是,您可以使用枚举来模拟 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();
}
}