本文介绍了静态vs实例变量:差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

静态变量和实例变量之间的区别是什么。下面的句子是我不能得到的:

What is the difference between a static and instance variable. The following sentence is what I cant get:

我认为实例vars使用的是类宽,而静态变量只有自己方法中的范围?

I thought that instance vars were used class wide whereas static variables only had scope within their own methods?

推荐答案

在类属性的上下文中, static 。如果你有一个字段:

In the context of class attributes, static has a different meaning. If you have a field like:

private static int sharedAttribute;

然后,每个实例同一变量,因此,如果您在一个实例中更改它,则更改将反映在更改之前或之后创建的所有实例中。

then, each and every instance of the class will share the same variable, so that if you change it in one instance, the change will reflect in all instances, created either before or after the change.

说,你可能会理解这在很多情况下是不好的,因为它可以很容易变成不希望的副作用:更改对象 a 也会影响 b ,你可能会想知道为什么 b 更改没有明显的原因。无论如何,这种行为是绝对需要的情况:

Thus said, you might understand that this is bad in many cases, because it can easiy turn into an undesired side-effect: changing object a also affects b and you might end up wondering why b changed with no apparent reasons. Anyway, there are cases where this behaviour is absolutely desirable:


  1. 类常量:因为它们 const ,所有的类访问相同的值将没有任何伤害,因为没有人可以改变。如果您有很多的类的实例,它们也可以节省内存。不知道并发访问。

  2. 要共享的变量,如引用计数器& / li>
  1. class constants: since they are const, having all the classes access the same value will do no harm, because no one can change that. They can save memory too, if you have a lot of instances of that class. Not sure about concurrent access, though.
  2. variables that are intended to be shared, such as reference counters &co.

static vars在程序启动之前被实例化,

static vars are instantiated before your program starts, so if you have too many of them, you could slow down startup.

A static 方法只能访问 static 属性,但在尝试之前要三思。

A static method can only access static attributes, but think twice before trying this.

经验法则:不要使用 static ,除非它是必要的,你知道你在做什么,或者你正在声明一个类常量。

Rule of thumb: don't use static, unless it is necessary and you know what you are doing or you are declaring a class constant.

这篇关于静态vs实例变量:差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:17