私人最终静态属性VS私人最终属性 [英] private final static attribute vs private final attribute

查看:132
本文介绍了私人最终静态属性VS私人最终属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,有什么区别:

In Java, what's the difference between:

private final static int NUMBER = 10;

private final int NUMBER = 10;

两者都是私人最后,所不同的是静态属性。

什么是好?为什么?

推荐答案

在一般情况下,静态表示用的键入的本身相关联,而类型比的实例的。

In general, static means "associated with the type itself, rather than an instance of the type."

这意味着你可以参考一个静态变量,而不必有史以来类型的情况下,任何code指变量指的是完全一样的数据。有一个实例变量的比较:在这种情况下,有每类的实例变量的一个独立版本。因此,例如:

That means you can reference a static variable without having ever created an instances of the type, and any code referring to the variable is referring to the exact same data. Compare this with an instance variable: in that case, there's one independent version of the variable per instance of the class. So for example:

Test x = new Test();
Test y = new Test();
x.instanceVariable = 10;
y.instanceVariable = 20;
System.out.println(x.instanceVariable);

打印出10: y.instanceVariable x.instanceVariable 是分开的,因为 X 引用不同的对象。

prints out 10: y.instanceVariable and x.instanceVariable are separate, because x and y refer to different objects.

您的通过引用可以的参考静态成员,尽管它是一个坏主意,这样做。如果我们这样做:

You can refer to static members via references, although it's a bad idea to do so. If we did:

Test x = new Test();
Test y = new Test();
x.staticVariable = 10;
y.staticVariable = 20;
System.out.println(x.staticVariable);

那么这将打印出20 - 这里只有一个变量,每个实例一个也没有。这本来是更清楚写为:

then that would print out 20 - there's only one variable, not one per instance. It would have been clearer to write this as:

Test x = new Test();
Test y = new Test();
Test.staticVariable = 10;
Test.staticVariable = 20;
System.out.println(Test.staticVariable);

这使得行为更加明显。现代的IDE通常建议改变第二上市到第三层。

That makes the behaviour much more obvious. Modern IDEs will usually suggest changing the second listing into the third.

有没有理由有一个声明,如

There is no reason to have a declaration such as

private final int NUMBER = 10;

如果它不能改变,还有是每个实例的一个副本没有意义。

If it cannot change, there is no point having one copy per instance.

这篇关于私人最终静态属性VS私人最终属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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