java对象,共享变量 [英] java objects, shared variables
问题描述
我有一个简单的问题.如果我在主类中[声明]的对象中声明一个变量,如下所示:
I have a simple question here. If I declare a variable inside an object which was made [declared] in the main class, like this:
public static int number;
(通常我会这样声明:
private int number;
)
它可以用于在主类中[声明]的不同对象吗?顺便说一句,我不在乎安全性 atm,我只想做点什么,不在乎保护)
can it be used in a different object which was also made [declared] in the main class? btw I do not care about security atm, I just want to make something work, don't care about protection)
推荐答案
这是 Java 语言规范中的一段引述:
Here's a telling quote from Java Language Specification:
如果一个字段被声明为static
,那么该字段只存在一个化身,无论最终创建了多少个类的实例(可能为零).static
字段,有时称为类变量,在类初始化时体现.
If a field is declared
static
, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. Astatic
field, sometimes called a class variable, is incarnated when the class is initialized.
未声明为static
的字段(有时称为非static
字段)称为实例变量.每当创建一个类的新实例时,都会为该类或其任何超类中声明的每个实例变量创建一个与该实例关联的新变量.
A field that is not declared static
(sometimes called a non-static
field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
[示例程序如下...]
简而言之,static
字段是一个 class 变量:它属于类,而不是类的实例.在某种程度上,您可以将 static
字段视为类的实例共享的变量,但将 static
字段视为属于该类会更加一致,就像static
方法也属于类等
In short, a static
field is a class variable: it belongs to the class, as opposed to the instances of the class. In a way, you can think of a static
field as a variable shared by instances of the class, but it's much more consistent to think of static
fields as belonging to the class, just like static
method also belongs to the class, etc.
由于它们属于类,因此不需要访问该类的实例(假设有足够的可见性),实际上,通过实例访问 static
成员被认为是不好的编程实践类型表达式.
Since they belong to the class, they do not require an instance of said class to access (assuming adequate visibility), and in fact it's considered bad programming practice to access static
members through an instance instead of a type expression.
这篇关于java对象,共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!