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. Astatic
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 methods best practices
> Static methods
> calling non-static method in static method in Java
> non-static variable cannot be referenced from a static context (java)
> When NOT to use the static keyword in Java?
> Static variables and methods
标签:java,static-members 来源: https://codeday.me/bug/20191002/1841732.html