在 Java 中何时使用静态变量/方法以及何时使用实例变量/方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21155438/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:58:34  来源:igfitidea点击:

When to use static variables/methods and when to use instance variables/methods in Java?

javastaticinstance

提问by user3133542

i would like to ask the question when it would be advantageous to use static variables/methods or in the other case instance variables/methods in Java?

我想问一个问题,什么时候在 Java 中使用静态变量/方法或在其他情况下使用实例变量/方法是有利的?

I know that it depends on the certain case (like programming util-classes as static methods), but can we declare something like a general strategy?

我知道这取决于特定情况(例如将实用程序类编程为静态方法),但是我们可以声明一些通用策略吗?

采纳答案by TheLostMind

At novice level :

在新手层面:

Use instance variables when : Every variable has a different value for different object. E.g. name of student, roll number etc..

在以下情况下使用实例变量:对于不同的对象,每个变量都有不同的值。例如学生姓名、卷号等。

use static variables when : The value of the variable is independent of the objects (not unique for each object). E.g. number of students.

在以下情况下使用静态变量:变量的值独立于对象(不是每个对象唯一的)。例如学生人数。

回答by Abimaran Kugathasan

staticvariables are often used for constants, which is common to all the instances if the class. For example, many people don't like to "hard-code" constants in their code; they like to make a public staticor private staticvariable with a meaningful name and use that in their code, which should make the code more readable.

static变量通常用于常量,如果是类,它对所有实例都是通用的。例如,许多人不喜欢在他们的代码中“硬编码”常量;他们喜欢用有意义的名称创建一个public staticprivate static变量并在他们的代码中使用它,这应该使代码更具可读性。

In Short

简而言之

Any method or variable that is independent of the state of an instance of the class should be static.

任何独立于类实例状态的方法或变量都应该是静态的

回答by Md. Yusuf

Static variable: When you need something that will be used through out the application and every instance need to know the variable.

静态变量:当您需要将在整个应用程序中使用的东西并且每个实例都需要知道该变量时。

Instance variable: It will be different from object to object and object's property while static variable is Class's property.

实例变量:它会因对象和对象的属性而异,而静态变量是类的属性。

Static function: Used to do some utility task. Can be called without any object declaration.

静态函数:用于执行一些实用任务。无需任何对象声明即可调用。

Instance function: Need object to call this function.

实例函数:需要对象来调用这个函数。

static or instance depends on your uses .

静态或实例取决于您的用途。

回答by Denis Kulagin

Think of static variables as class-wide global variables or, if you use "final" keyword, as class-wide global constants. Use static non-final variables wisely - they are shared among all class instances and it may lead to some non-obvious mistakes. I would recomend avoid using mutable static variables at all - there are small to none cases, where such need couldn't be implemented using dependency injection.

将静态变量视为类范围的全局变量,或者,如果使用“final”关键字,则视为类范围的全局常量。明智地使用静态非最终变量 - 它们在所有类实例之间共享,这可能会导致一些不明显的错误。我建议完全避免使用可变静态变量 - 有很少甚至没有的情况,使用依赖注入无法实现这种需求。

Also using globals always makes unit-testing lot harder - one more drawback to consider.

同样使用全局变量总是会使单元测试变得更加困难——还有一个需要考虑的缺点。

回答by Erwin Smout

As for methods : every method Foo.method(Bar1 b1, Bar2, b2)by definition could always have alternative equivalent designs:

至于方法:Foo.method(Bar1 b1, Bar2, b2)根据定义,每种方法总是可以有替代的等效设计:

Bar.altmethod(Foo f, Bar b2)

Bar.altmethod(Foo f, Bar b2)

and

static staticMethod(Foo f, Bar b1, Bar b2)

static staticMethod(Foo f, Bar b1, Bar b2)

And you could also wrap that latter method as an instance method in a service class which is itself a singleton (so that the static-ness of the method is a bit little bit concealed by the class it's in).

您还可以将后一种方法作为实例方法包装在一个服务类中,该类本身是一个单例(这样方法的静态性就会被它所在的类稍微隐藏起来)。

The only compellingreason to have your method as an instance method of the class of one of your method arguments (of the static version), is when you expect there to be subclasses for that class, and that it might be useful for those subclasses to have a specialized implementation of the method.

将您的方法作为您的方法参数之一(静态版本)的类的实例方法的唯一令人信服的理由是,当您希望该类有子类时,并且它可能对这些子类有用有一个专门的方法实现。

Imagine

想象

class GeographicalFigure {
    Object quadrature() { ... }
}

It might be useful to leave open the possibility of later adding

保留以后添加的可能性可能会很有用

class Circle extends GeographicalFigure {
    Object quadrature() {
        throw new ThisIsNoGoodException();
    }
}

Other than that, all your options are essentially equivalent.

除此之外,您的所有选项本质上都是相同的。