java 变量共享_java对象,共享变量
我這里有一個簡單的問題.
如果我在一個在主類中聲明[聲明]的對象中聲明一個變量,如下所示:
public static int number;
(
通常我這樣聲明:
private int number;
)
它可以用在主要類中也被聲明的不同對象中嗎?
順便說一句我不關心安全問題,我只想做點工作,不關心保護)
解決方法:
這是Java語言規范的一個引人注目的引用:
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. A static field, sometimes called a class variable, is incarnated when the class is initialized.
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.
[Example program follows…]
簡而言之,靜態字段是一個類變量:它屬于類,而不是類的實例.在某種程度上,您可以將靜態字段視為由類的實例共享的變量,但將靜態字段視為屬于該類更加一致,就像靜態方法也屬于類等一樣.
由于它們屬于該類,因此它們不需要所述類的實例來訪問(假設足夠的可見性),并且實際上通過實例而不是類型表達式訪問靜態成員被認為是不好的編程習慣.
相關問題
標簽:java,static-members
來源: https://codeday.me/bug/20191002/1841732.html
總結
以上是生活随笔為你收集整理的java 变量共享_java对象,共享变量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 免疫因子的作用是什么
- 下一篇: 按摩腰部的方法有什么