在 Java 中如何以及在何处使用静态修饰符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3963983/
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
How and where to use Static modifier in Java?
提问by zengr
How and where should we use a Static modifier for:
我们应该如何以及在哪里使用静态修饰符:
1. Field and
2. Method?
1. 领域和
2. 方法?
For examplein java.lang.Math
class, the fields methods like abs(), atan(), cos() etc are static, i.e. they can be accessed as: Math.abs()
对于例如在java.lang.Math
类中,字段的方法,如ABS(),ATAN(),COS()等是静态的,即它们可以作为被访问:Math.abs()
But why is it a good practice?
但为什么这是一个好习惯呢?
Say, I don't keep it static and create an object of the class and access it, which anyways I can, I will just get a warning that, you are trying to access a static method in a non static way (as pointed out by @duffymo, not in case of Math class).
说,我不让它保持静态并创建类的对象并访问它,无论如何我可以,我只会收到警告,您正在尝试以非静态方式访问静态方法(如所指出的那样)由@duffymo 提供,不适用于数学课)。
UPDATE 1:
更新1:
So, utility method, should be static, i.e. whose work is only dependent on the method parameters. So, for example, can the method updateString(String inputQuery, String highlightDoc)
should have been a static method in this question?
因此,实用方法应该是静态的,即其工作仅依赖于方法参数。那么,例如,该方法updateString(String inputQuery, String highlightDoc)
是否应该是这个问题中的静态方法?
采纳答案by Alex
You can think of a 'static' method or field as if it were declared outside the class definition. In other words
您可以将“静态”方法或字段视为在类定义之外声明。换句话说
- There is only one 'copy' of a static field/method.
- Static fields/methods cannot access non-static fields/methods.
- 静态字段/方法只有一个“副本”。
- 静态字段/方法无法访问非静态字段/方法。
There are several instances where you would want to make something static.
在某些情况下,您可能希望将某些内容设为静态。
The canonical example for a field is to make a static integer field which keeps a count across all instances (objects) of a class. Additionally, singleton objects, for example, also typically employ the static modifier.
字段的规范示例是创建一个静态整数字段,该字段保持一个类的所有实例(对象)的计数。此外,例如,单例对象通常也使用静态修饰符。
Similarly, static methods can be used to perform 'utility' jobs for which all the required dependencies are passed in as parameters to the method - you cannot reference the 'this' keyword inside of a static method.
类似地,静态方法可用于执行“实用程序”作业,其中所有必需的依赖项都作为参数传递给方法——您不能在静态方法中引用“this”关键字。
In C#, you can also have static classes which, as you might guess, contain only static members:
在 C# 中,您还可以拥有静态类,正如您可能猜到的那样,这些类只包含静态成员:
public static class MyContainer
{
private static int _myStatic;
public static void PrintMe(string someString)
{
Console.Out.WriteLine(someString);
_myStatic++;
}
public static int PrintedInstances()
{
return _myStatic;
}
}
回答by Fge
Usually when the method only depends on the function parameters and not on the internal state of the object it's a static method (with singletone being the only exception). I can't imagine where static fields are really used (they're the same as global variables which should be avoided).
Like in your example the math functions only depend on the parameters.
通常当方法只依赖于函数参数而不依赖于对象的内部状态时,它是一个静态方法(单调是唯一的例外)。我无法想象真正使用静态字段的地方(它们与应该避免的全局变量相同)。
就像在您的示例中一样,数学函数仅取决于参数。
回答by duffymo
You can't instantiate an instance of java.lang.Math; there isn't a public constructor.
你不能实例化 java.lang.Math 的实例;没有公共构造函数。
Try it:
尝试一下:
public class MathTest
{
public static void main(String [] args)
{
Math math = new Math();
System.out.println("math.sqrt(2) = " + math.sqrt(2));
}
}
Here's what you'll get:
这是你会得到的:
C:\Documents and Settings\Michael\My Documents\MathTest.java:5: Math() has private access in java.lang.Math
Math math = new Math();
^
1 error
Tool completed with exit code 1
回答by pilotgallo2
For a field you should keep it static if you want all instances of a given class to have access to its value. For example if I have
对于一个字段,如果您希望给定类的所有实例都可以访问其值,则应将其保持为静态。例如,如果我有
public static int age = 25;
Then any instance of the class can get or set the value of age with all pointing to the same value. If you do make something static you run the risk of having two instances overwriting each others values and possibly causing problems.
然后该类的任何实例都可以获取或设置所有指向相同值的 age 值。如果您确实将某些内容设为静态,则有两个实例会覆盖彼此的值并可能导致问题的风险。
The reason to create static methods is mostly for utility function where all the required data for the method is passed in and you do not want to take the over head of creating an instance of the class each time you want to call the method.
创建静态方法的原因主要是为了实用程序函数,其中传递了该方法所需的所有数据,并且您不想在每次要调用该方法时都创建类的实例。
回答by Niko
Static uses less memory since it exists only once per Classloader.
静态使用较少的内存,因为它每个类加载器只存在一次。
To have methods static may save some time, beacuse you do not have to create an object first so you can call a function. You can/should use static methods when they stand pretty much on their own (ie. Math.abs(X) - there really is no object the function needs.) Basically its a convenience thing (at least as far as I see it - others might and will disagree :P)
使用静态方法可能会节省一些时间,因为您不必先创建对象就可以调用函数。您可以/应该在静态方法几乎独立时使用它们(即 Math.abs(X) - 确实没有函数需要的对象。)基本上它是一件方便的事情(至少在我看来 -其他人可能并且会不同意:P)
Static fields should really be used with caution. There are quite a few patterns that need static fields... but the basics first:
静态字段确实应该谨慎使用。有很多模式需要静态字段......但首先是基础知识:
a static field exists only once. So if you have a simple class (kinda pseudocode):
静态字段只存在一次。所以如果你有一个简单的类(有点伪代码):
class Simple {
static int a;
int b;
}
and now you make objects with:
现在你用以下方法制作对象:
Simple myA = new Simple();
Simple myB = new Simple();
myA.a = 1;
myA.b = 2;
myB.a = 3;
myB.b = 4;
System.out.println(myA.a + myA.b + myB.a + myB.b);
you will get 3234 - because by setting myB.a you actually overwrite myA.a as well because a is static. It exists in one place in memory.
你会得到 3234 - 因为通过设置 myB.a 你实际上也覆盖了 myA.a 因为 a 是静态的。它存在于内存中的一处。
You normally want to avoid this because really weird things might happen. But if you google for example for Factory Patternyou will see that there are actually quite useful uses for this behaviour.
您通常希望避免这种情况,因为可能会发生非常奇怪的事情。但是如果你用谷歌搜索工厂模式,你会发现这种行为实际上有很多有用的用途。
Hope that clears it up a little.
希望能稍微澄清一下。
回答by TheJediCowboy
Try taking a look at this post, it also gives some examples of when to and when not to use static and final modifiers.
尝试看一下这篇文章,它还提供了一些何时使用静态和最终修饰符以及何时不使用的示例。
Most of the posts above are similar, but this post might offer some other insight.
When to use Static Modifiers
上面的大多数帖子都是相似的,但这篇文章可能会提供一些其他的见解。
何时使用静态修改器
回答by Bidyut Das
class StaticModifier
{
{
System.out.println("Within init block");//third
}
public StaticModifier()
{
System.out.println("Within Constructor");//fourth
}
public static void main(String arr[])
{
System.out.println("Within Main:");//second
//StaticModifier obj=new StaticModifier();
}
static
{
System.out.print("Within static block");//first
}
}