通俗地说,Java 中的“静态”是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2649213/
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
In laymans terms, what does 'static' mean in Java?
提问by Philip Strong
I have been told several definitions for it, looked on Wikipedia, but as a beginner to Java I'm still not sure what it means. Anybody fluent in Java and idiot?
我在维基百科上看到了它的几个定义,但作为 Java 的初学者,我仍然不确定它的含义。有人精通Java和白痴吗?
采纳答案by inkedmn
static means that the variable or method marked as such is available at the class level. In other words, you don't need to create an instance of the class to access it.
静态意味着标记为此类的变量或方法在类级别可用。换句话说,您不需要创建类的实例来访问它。
public class Foo {
public static void doStuff(){
// does stuff
}
}
So, instead of creating an instance of Foo and then calling doStuff
like this:
因此,不要创建 Foo 的实例,然后doStuff
像这样调用:
Foo f = new Foo();
f.doStuff();
You just call the method directly against the class, like so:
您只需直接针对类调用该方法,如下所示:
Foo.doStuff();
回答by Bostone
In very laymen terms the class is a mold and the object is the copy made with that mold. Static belong to the mold and can be accessed directly without making any copies, hence the example above
在非常外行的术语中,类是一个模具,而对象是用该模具制作的副本。静态属于模具,可以直接访问而无需进行任何复制,因此上面的示例
回答by wulfgarpro
In addition to what @inkedmn has pointed out, a static member is at the class level. Therefore, the said member is loaded into memory by the JVM once for that class (when the class is loaded). That is, there aren't ninstances of a static member loaded for ninstances of the class to which it belongs.
除了@inkedmn 指出的之外,静态成员位于类级别。因此,JVM为该类将所述成员加载到内存中(在加载类时)。也就是说,有不Ñ的静态成员的情况下加载Ñ它所属的类的实例。
回答by mel3kings
Another great example of when static attributesand operations are used when you want to apply the Singletondesign pattern. In a nutshell, the Singleton design pattern ensures that one and only one object of a particular class is ever constructeed during the lifetime of your system. to ensure that only one object is ever constructed, typical implemenations of the Singleton pattern keep an internal static reference to the single allowed object instance, and access to that instance is controlled using a static
operation
当您想要应用单例设计模式时,使用静态属性和操作的另一个很好的例子。简而言之,Singleton 设计模式确保在您的系统的生命周期内只构造一个特定类的一个对象。为了确保只构造一个对象,单例模式的典型实现保持对单个允许的对象实例的内部静态引用,并使用static
操作控制对该实例的访问
回答by sushanth
Above points are correct and I want to add some more important points about Static keyword.
以上几点是正确的,我想添加一些关于 Static 关键字的更重要的观点。
Internally what happening when you are using static keyword is it will store in permanent memory(that is in heap memory),we know that there are two types of memory they are stack memory(temporary memory) and heap memory(permanent memory),so if you are not using static key word then will store in temporary memory that is in stack memory(or you can call it as volatile memory).
在内部使用 static 关键字时发生的情况是它将存储在永久内存中(即堆内存中),我们知道有两种类型的内存,它们是堆栈内存(临时内存)和堆内存(永久内存),所以如果您不使用静态关键字,则将存储在堆栈内存中的临时内存中(或者您可以将其称为易失性内存)。
so you will get a doubt that what is the use of this right???
所以你会怀疑这个权利有什么用???
example: static int a=10;(1 program)
示例:静态 int a=10;(1 个程序)
just now I told if you use static keyword for variablesor for methodit will store in permanent memoryright.
刚才我告诉你,如果你对变量或方法使用 static 关键字,它将存储在永久内存中。
so I declared same variable with keyword staticin other program with different value.
所以我 在其他具有不同值的程序中用关键字static声明了相同的变量。
example: static int a=20;(2 program)
示例:静态 int a=20;(2 个程序)
the variable 'a' is stored in heap memory by program 1.the same static variable 'a' is found in program 2at that time it won`t create once again 'a' variable in heap memory instead of that it just replace value of a from 10 to 20.
变量 'a' 由程序 1存储在堆内存中。当时在程序 2中发现了相同的静态变量 'a' ,它不会在堆内存中再次创建变量 'a' 而不是它只是替换值从 10 到 20。
In general it will create once againvariable 'a' in stack memory(temporary memory) if you won`t declare 'a' as static variable.
通常,如果您不将“a”声明为静态变量,它将在堆栈内存(临时内存)中再次创建变量“a”。
overall i can say that,if we use static keyword
1.we can save memory
2.we can avoid duplicates
3.No need of creating object in-order to access static variable with the help of class name you can access it.
总的来说,我可以说,如果我们使用静态关键字
1.我们可以节省内存
2.我们可以避免重复
3.无需创建对象 - 借助类名访问静态变量,您可以访问它。
回答by Pace
The static keyword can be used in several different ways in Java and in almost all cases it is a modifier which means the thing it is modifying is usable without an enclosing object instance.
static 关键字可以在 Java 中以多种不同的方式使用,并且在几乎所有情况下它都是一个修饰符,这意味着它正在修改的东西可以在没有封闭对象实例的情况下使用。
Java is an object oriented language and by default most code that you write requires an instance of the object to be used.
Java 是一种面向对象的语言,默认情况下,您编写的大多数代码都需要使用对象的实例。
public class SomeObject {
public int someField;
public void someMethod() { };
public Class SomeInnerClass { };
}
In order to use someField, someMethod, or SomeInnerClass I have to first create an instance of SomeObject.
为了使用 someField、someMethod 或 SomeInnerClass,我必须首先创建 SomeObject 的实例。
public class SomeOtherObject {
public void doSomeStuff() {
SomeObject anInstance = new SomeObject();
anInstance.someField = 7;
anInstance.someMethod();
//Non-static inner classes are usually not created outside of the
//class instance so you don't normally see this syntax
SomeInnerClass blah = anInstance.new SomeInnerClass();
}
}
If I declare those things static then they do not require an enclosing instance.
如果我声明这些东西是静态的,那么它们就不需要一个封闭的实例。
public class SomeObjectWithStaticStuff {
public static int someField;
public static void someMethod() { };
public static Class SomeInnerClass { };
}
public class SomeOtherObject {
public void doSomeStuff() {
SomeObjectWithStaticStuff.someField = 7;
SomeObjectWithStaticStuff.someMethod();
SomeObjectWithStaticStuff.SomeInnerClass blah = new SomeObjectWithStaticStuff.SomeInnerClass();
//Or you can also do this if your imports are correct
SomeInnerClass blah2 = new SomeInnerClass();
}
}
Declaring something static has several implications.
声明一些静态的东西有几个含义。
First, there can only ever one value of a static field throughout your entire application.
首先,在整个应用程序中只能有一个静态字段的值。
public class SomeOtherObject {
public void doSomeStuff() {
//Two objects, two different values
SomeObject instanceOne = new SomeObject();
SomeObject instanceTwo = new SomeObject();
instanceOne.someField = 7;
instanceTwo.someField = 10;
//Static object, only ever one value
SomeObjectWithStaticStuff.someField = 7;
SomeObjectWithStaticStuff.someField = 10; //Redefines the above set
}
}
The second issue is that static methods and inner classes cannot access fields in the enclosing object(since there isn't one).
第二个问题是静态方法和内部类不能访问封闭对象中的字段(因为没有)。
public class SomeObjectWithStaticStuff {
private int nonStaticField;
private void nonStaticMethod() { };
public static void someStaticMethod() {
nonStaticField = 7; //Not allowed
this.nonStaticField = 7; //Not allowed, can never use *this* in static
nonStaticMethod(); //Not allowed
super.someSuperMethod(); //Not allowed, can never use *super* in static
}
public static class SomeStaticInnerClass {
public void doStuff() {
someStaticField = 7; //Not allowed
nonStaticMethod(); //Not allowed
someStaticMethod(); //This is ok
}
}
}
The static keyword can also be applied to inner interfaces, annotations, and enums.
static 关键字还可以应用于内部接口、注释和枚举。
public class SomeObject {
public static interface SomeInterface { };
public static @interface SomeAnnotation { };
public static enum SomeEnum { };
}
In all of these cases the keyword is redundant and has no effect. Interfaces, annotations, and enums are static by default because they never have a relationship to an inner class.
在所有这些情况下,关键字都是多余的,没有效果。默认情况下,接口、注释和枚举是静态的,因为它们与内部类没有关系。
This just describes what they keyword does. It does not describe whether the use of the keyword is a bad idea or not. That can be covered in more detail in other questions such as Is using a lot of static methods a bad thing?
这只是描述了他们关键字的作用。它没有描述使用关键字是否是一个坏主意。这可以在其他问题中更详细地涵盖,例如使用大量静态方法是一件坏事吗?
There are also a few less common uses of the keyword static. There are static imports which allow you to use static types (including interfaces, annotations, and enums not redundantly marked static) unqualified.
关键字 static 也有一些不太常见的用法。有一些静态导入允许您使用未限定的静态类型(包括接口、注释和未冗余标记为静态的枚举)。
//SomeStaticThing.java
public class SomeStaticThing {
public static int StaticCounterOne = 0;
}
//SomeOtherStaticThing.java
public class SomeOtherStaticThing {
public static int StaticCounterTwo = 0;
}
//SomeOtherClass.java
import static some.package.SomeStaticThing.*;
import some.package.SomeOtherStaticThing.*;
public class SomeOtherClass {
public void doStuff() {
StaticCounterOne++; //Ok
StaticCounterTwo++; //Not ok
SomeOtherStaticThing.StaticCounterTwo++; //Ok
}
}
Lastly, there are static initializers which are blocks of code that are run when the class is first loaded (which is usuallyjust before a class is instantiated for the first time in an application) and (like static methods) cannot access non-static fields or methods.
最后,静态初始化程序是在类首次加载时运行的代码块(通常在应用程序中第一次实例化类之前)并且(如静态方法)不能访问非静态字段或方法。
public class SomeObject {
private static int x;
static {
x = 7;
}
}