Java 'static' 关键字在类中有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/413898/
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
What does the 'static' keyword do in a class?
提问by Click Upvote
To be specific, I was trying this code:
具体来说,我正在尝试以下代码:
package hello;
public class Hello {
Clock clock = new Clock();
public static void main(String args[]) {
clock.sayTime();
}
}
But it gave the error
但它给出了错误
Cannot access non-static field in static method main
无法访问静态方法 main 中的非静态字段
So I changed the declaration of clock
to this:
所以我把声明改成clock
这样:
static Clock clock = new Clock();
And it worked. What does it mean to put that keyword before the declaration? What exactly will it do and/or restrict in terms of what can be done to that object?
它奏效了。将该关键字放在声明之前是什么意思?就可以对该对象执行的操作而言,它究竟会做什么和/或限制什么?
采纳答案by Mehrdad Afshari
static
members belong to the class instead of a specific instance.
static
成员属于类而不是特定实例。
It means that only one instance of a static
field exists[1]even if you create a million instances of the class or you don't create any. It will be shared by all instances.
这意味着即使您创建了该类的一百万个实例或不创建任何实例,static
也只存在一个字段实例[1]。它将被所有实例共享。
Since static
methods also do not belong to a specific instance, they can't refer to instance members. In the example given, main
does not know which instance of the Hello
class (and therefore which instance of the Clock
class) it should refer to. static
members can only refer to static
members. Instance members can, of course access static
members.
由于static
方法也不属于特定实例,因此它们不能引用实例成员。在给出的示例中,main
不知道它应该引用类的Hello
哪个实例(以及类的哪个实例Clock
)。static
会员只能指static
会员。实例成员当然可以访问static
成员。
Side note:Of course, static
members can access instance members through an object reference.
旁注:当然,static
成员可以通过对象引用访问实例成员。
Example:
例子:
public class Example {
private static boolean staticField;
private boolean instanceField;
public static void main(String[] args) {
// a static method can access static fields
staticField = true;
// a static method can access instance fields through an object reference
Example instance = new Example();
instance.instanceField = true;
}
[1]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point.
[1]:根据运行时特性,它可以是每个 ClassLoader、AppDomain 或线程一个,但这不是重点。
回答by Elie
Static means that you don't have to create an instance of the class to use the methods or variables associated with the class. In your example, you could call:
静态意味着您不必创建类的实例来使用与类关联的方法或变量。在您的示例中,您可以调用:
Hello.main(new String[]()) //main(...) is declared as a static function in the Hello class
directly, instead of:
直接,而不是:
Hello h = new Hello();
h.main(new String[]()); //main(...) is a non-static function linked with the "h" variable
From inside a static method (which belongs to a class) you cannot access any members which are not static, since their values depend on your instantiation of the class. A non-static Clock object, which is an instance member, would have a different value/reference for each instance of your Hello class, and therefore you could not access it from the static portion of the class.
从静态方法(属于类)内部,您无法访问任何非静态成员,因为它们的值取决于您对类的实例化。作为实例成员的非静态 Clock 对象对于 Hello 类的每个实例都有不同的值/引用,因此您无法从类的静态部分访问它。
回答by Paul Tomblin
It means that there is only one instance of "clock" in Hello, not one per each separate instance of the "Hello" class, or more-so, it means that there will be one commonly shared "clock" reference among all instances of the "Hello" class.
这意味着 Hello 中只有一个“clock”实例,而不是每个“Hello”类的每个单独实例都有一个实例,或者更多,这意味着在所有实例之间将有一个共同共享的“clock”引用“你好”类。
So if you were to do a "new Hello" anywhere in your code: A- in the first scenario (before the change, without using "static"), it would make a new clock every time a "new Hello" is called, but B- in the second scenario (after the change, using "static"), every "new Hello" instance would still share and use the initial and same "clock" reference first created.
因此,如果您要在代码中的任何位置执行“new Hello”:A- 在第一种情况下(更改之前,不使用“static”),每次调用“new Hello”时都会创建一个新时钟,但是 B- 在第二种情况下(更改后,使用“静态”),每个“新 Hello”实例仍将共享和使用最初创建的初始和相同的“时钟”引用。
Unless you needed "clock" somewhere outside of main, this would work just as well:
除非您在 main 之外的某个地方需要“时钟”,否则这也能正常工作:
package hello;
public class Hello
{
public static void main(String args[])
{
Clock clock=new Clock();
clock.sayTime();
}
}
回答by Stephen Doyle
Static makes the clock member a class member instead of an instance member. Without the static keyword you would need to create an instance of the Hello class (which has a clock member variable) - e.g.
静态使时钟成员成为类成员而不是实例成员。如果没有 static 关键字,您将需要创建 Hello 类的实例(它有一个时钟成员变量) - 例如
Hello hello = new Hello();
hello.clock.sayTime();
回答by Marc Novakowski
回答by sblundy
A field can be assigned to either the class or an instance of a class. By default fields are instance variables. By using static
the field becomes a class variable, thus there is one and only one clock
. If you make a changes in one place, it's visible everywhere. Instance varables are changed independently of one another.
字段可以分配给类或类的实例。默认情况下,字段是实例变量。通过使用static
该字段成为一个类变量,因此只有一个clock
。如果您在一个地方进行更改,则它在任何地方都可见。实例变量相互独立地改变。
回答by Julien Chastang
This discussion has so far ignored classloader considerations. Strictly speaking, Java static fields are shared between all instances of a class for a given classloader.
到目前为止,这个讨论忽略了类加载器的考虑。严格来说,Java 静态字段在给定类加载器的类的所有实例之间共享。
回答by kal
Can also think of static members not having a "this" pointer. They are shared among all instances.
也可以认为静态成员没有“this”指针。它们在所有实例之间共享。
回答by geowa4
The static
keyword in Java means that the variable or function is shared between all instances of that class as it belongs to the type, not the actual objects themselves.
static
Java 中的关键字意味着变量或函数在该类的所有实例之间共享,因为它属于type,而不是实际对象本身。
So if you have a variable: private static int i = 0;
and you increment it (i++
) in one instance, the change will be reflected in all instances. i
will now be 1 in all instances.
因此,如果您有一个变量:private static int i = 0;
并且i++
在一个实例中增加它 ( ),则更改将反映在所有实例中。i
现在在所有情况下都是 1。
Static methods can be used without instantiating an object.
可以在不实例化对象的情况下使用静态方法。
回答by Jon Skeet
The static
keyword means that something (a field, method or nested class) is related to the typerather than any particular instanceof the type. So for example, one calls Math.sin(...)
without any instance of the Math
class, and indeed you can'tcreate an instance of the Math
class.
的static
关键字的装置的东西(字段,方法或嵌套类)是有关类型,而不是任何特定的实例的类型。因此,例如,在Math.sin(...)
没有任何Math
类实例的情况下调用,实际上您无法创建Math
类的实例。
For more information, see the relevant bit of Oracle's Java Tutorial.
有关更多信息,请参阅Oracle 的 Java 教程的相关部分。
Sidenote
边注
Java unfortunately allowsyou to access static members as if they were instance members, e.g.
不幸的是,Java允许您像访问实例成员一样访问静态成员,例如
// Bad code!
Thread.currentThread().sleep(5000);
someOtherThread.sleep(5000);
That makes it lookas if sleep
is an instance method, but it's actually a static method - it alwaysmakes the current thread sleep. It's better practice to make this clear in the calling code:
这使它看起来好像sleep
是一个实例方法,但它实际上是一个静态方法 - 它总是使当前线程休眠。在调用代码中明确这一点是更好的做法:
// Clearer
Thread.sleep(5000);