静态变量与实例变量:区别? [英] Static vs Instance Variables: Difference?

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

问题描述

静态变量和实例变量有什么区别.下面这句话是我无法理解的:

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

在某些情况下,一个类的所有对象应该只共享一个特定变量的一个副本——这里使用的是静态变量.
静态变量代表类范围的信息.一个类的所有对象共享相同的数据.

In certain cases, only one copy of a particular variable should be shared by all objects of a class- here a static variable is used.
A static variable represents class wide info.All objects of a class share the same data.

我认为实例变量在类范围内使用,而静态变量只在它们自己的方法内有作用域?

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. 打算共享的变量,例如引用计数器 &co.
  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 变量在你的程序启动之前被实例化,所以如果你有太多的变量,你可能会减慢启动速度.

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

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆