为什么Java中没有Constant特性?
我试图找出 Java 中常量背后的原因 我了解到Java允许我们使用final
关键字声明常量。
我的问题是为什么 Java 没有引入常量 (const
) 功能。由于很多人说它来自C++,所以在C++中我们有const
关键字。
请分享您的想法。
I was trying to identify the reason behind constants in Java
I have learned that Java allows us to declare constants by using final
keyword.
My question is why didn't Java introduce a Constant (const
) feature. Since many people say it has come from C++, in C++ we have const
keyword.
Please share your thoughts.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
每次我从繁重的 C++ 编码转向 Java 时,我都会花一些时间来适应 的缺乏Java 中的 const 正确性。如果您不知道的话,C++ 中
const
的用法与声明常量变量有很大不同。本质上,它确保对象在通过一种称为 const 指针的特殊指针访问时是不可变的。在 Java 中,在我通常想要返回 const 指针的地方,我会返回一个带有接口类型的引用仅包含不应该有副作用的方法。不幸的是,这不是由语言强制执行的。维基百科提供了有关该主题的以下信息:
Every time I go from heavy C++ coding to Java, it takes me a little while to adapt to the lack of const-correctness in Java. This usage of
const
in C++ is much different than just declaring constant variables, if you didn't know. Essentially, it ensures that an object is immutable when accessed through a special kind of pointer called a const-pointer When in Java, in places where I'd normally want to return a const-pointer, I instead return a reference with an interface type containing only methods that shouldn't have side effects. Unfortunately, this isn't enforced by the langauge.Wikipedia offers the following information on the subject:
const
是什么意思首先,认识到“const”关键字的语义对不同的人意味着不同的东西:
final
语义 - 引用变量本身不能重新分配给点到另一个实例(内存位置),但实例本身是可修改的const
指针/引用语义 - 意味着此引用不能用于修改实例(例如,不能分配给实例变量,不能调用可变方法) - 仅影响引用变量,因此指向同一实例的非常量引用可以修改实例为什么或为什么不
const
其次,如果您确实想深入了解一些“赞成”与“反对”的论点,请参阅此增强请求 (RFE)“错误”下的讨论。该 RFE 请求“只读参考”类型的“const”功能。 “const”主题于 1999 年开放,然后于 2005 年被 Sun 关闭/拒绝,引起了激烈的争论:
https://bugs.java.com/bugdatabase/view_bug?bug_id=4211070
虽然双方都有很多很好的论点,但有些经常引用的(但不一定令人信服或明确的)反对
const
的理由包括:是什么? const 意思是上面的)
在有人试图与我争论这些理由是好是坏之前,请注意这些不是我的理由。它们只是我从 RFE 讨论中收集到的一些原因的“要点”。我自己不一定同意他们的观点 - 我只是想说明为什么有些人(不是我)可能觉得 const 关键字可能不是一个好主意。就我个人而言,我希望以明确的方式将更多“const”语义引入到该语言中。
What does
const
meanFirst, realize that the semantics of a "const" keyword means different things to different people:
final
semantics - reference variable itself cannot be reassigned to point to another instance (memory location), but the instance itself is modifiableconst
pointer/reference semantics - means this reference cannot be used to modify the instance (e.g. cannot assign to instance variables, cannot invoke mutable methods) - affects the reference variable only, so a non-const reference pointing to the same instance could modify the instanceWhy or Why Not
const
Second, if you really want to dig into some of the "pro" vs "con" arguments, see the discussion under this request for enhancement (RFE) "bug". This RFE requests a "readable-only reference"-type "const" feature. Opened in 1999 and then closed/rejected by Sun in 2005, the "const" topic was vigorously debated:
https://bugs.java.com/bugdatabase/view_bug?bug_id=4211070
While there are a lot of good arguments on both sides, some of the oft-cited (but not necessarily compelling or clear-cut) reasons against
const
include:const
mean above)Before anyone tries to debate me about whether these are good or bad reasons, note that these are not my reasons. They are simply the "gist" of some of the reasons I gleaned from skimming the RFE discussion. I don't necessarily agree with them myself - I'm simply trying to cite why some people (not me) may feel a
const
keyword may not be a good idea. Personally, I'd love more "const" semantics to be introduced to the language in an unambiguous manner.C++ 中的
const
并不意味着值是常量。C++ 中的 const 意味着合约的客户端承诺不改变其值。
如果您处于支持基于线程的并发性的环境中,
const
表达式的值是否发生变化会变得更加明显。由于 Java 从一开始就被设计为支持线程和锁并发,因此它并没有通过重载该术语来获得
final
所具有的语义来增加混乱。例如:
输出 42,然后输出 7。
虽然
x
标记为const
,但由于创建了非常量别名,所以x
不是常量。并非每个编译器都需要易失性
来实现此行为(尽管每个编译器都允许内联常量)。对于更复杂的系统,您无需使用
const_cast
即可获得 const/非常量别名,因此,养成认为 const 意味着某些东西不会改变的习惯变得越来越危险。const
仅仅意味着您的代码如果不进行强制转换就无法更改它,而不是说该值是常量。const
in C++ does not mean that a value is a constant.const
in C++ implies that the client of a contract undertakes not to alter its value.Whether the value of a
const
expression changes becomes more evident if you are in an environment which supports thread based concurrency.As Java was designed from the start to support thread and lock concurrency, it didn't add to confusion by overloading the term to have the semantics that
final
has.eg:
outputs 42 then 7.
Although
x
marked asconst
, as a non-const alias is created,x
is not a constant. Not every compiler requiresvolatile
for this behaviour (though every compiler is permitted to inline the constant)With more complicated systems you get const/non-const aliases without use of
const_cast
, so getting into the habit of thinking that const means something won't change becomes more and more dangerous.const
merely means that your code can't change it without a cast, not that the value is constant.这是一个有点老的问题,但我想无论如何我都会贡献我的 2 美分,因为今天的对话中出现了这个话题。
这并不能完全回答为什么没有 const?,而是如何让你的类不可变。 (不幸的是,我还没有足够的声誉来发布对已接受答案的评论)
保证对象不变性的方法是更仔细地设计你的类以使其不可变。这比可变类需要更多的关注。
这可以追溯到 Josh Bloch 的Effective Java项目 15 - 最小化可变性。如果您还没有读过这本书,请拿起一本并读几遍,我保证它将增强您的比喻“java游戏”。
在第 15 项中,Bloch 建议您应该限制类的可变性以确保对象的状态。
直接引用这本书:
然后,Bloch 描述了如何通过以下 5 个简单规则使类不可变:
final
)。最终
。私有
。有关更多详细信息,我强烈建议您拿起这本书的副本。
This is a bit of an old question, but I thought I would contribute my 2 cents anyway since this thread came up in conversation today.
This doesn't exactly answer why is there no const? but how to make your classes immutable. (Unfortunately I have not enough reputation yet to post as a comment to the accepted answer)
The way to guarantee immutability on an object is to design your classes more carefully to be immutable. This requires a bit more care than a mutable class.
This goes back to Josh Bloch's Effective Java Item 15 - Minimize Mutability. If you haven't read the book, pick up a copy and read it over a few times I guarantee it will up your figurative "java game".
In item 15 Bloch suggest that you should limit the mutability of classes to ensure the object's state.
To quote the book directly:
Bloch then describes how to make your classes immutable, by following 5 simple rules:
final
).final
.private
.For more details I highly recommend picking up a copy of the book.
C++ 的
const
语义与 Javafinal
非常不同。如果设计者使用const
,那就会造成不必要的混乱。const
是一个保留字,这一事实表明设计者曾有实现const
的想法,但后来他们决定不这样做;请参阅此已关闭的错误。所述原因包括添加对 C++ 风格const
的支持会导致兼容性问题。The C++ semantics of
const
are very different from Javafinal
. If the designers had usedconst
it would have been unnecessarily confusing.The fact that
const
is a reserved word suggests that the designers had ideas for implementingconst
, but they have since decided against it; see this closed bug. The stated reasons include that adding support for C++ styleconst
would cause compatibility problems.根据我引用的一本教科书的说法,
“const 是 Java 关键字,但现在不使用它来创建常量。因此,您需要使用 Final 关键字”
According to one of the text book that I have refered tells that,
"const is a Java keyword but it is not being used now to create constants. so, you need to use final keyword"
有一种方法可以在 Java 中创建“const”变量,但仅限于特定类。只需定义一个具有最终属性的类并对其进行子类化即可。然后使用您想要使用“const”的基类。同样,如果您需要使用“const”方法,请将它们添加到基类中。编译器不会允许你修改它认为是基类的final方法,但它会读取并调用子类的方法。
There is a way to create "const" variables in Java, but only for specific classes. Just define a class with final properties and subclass it. Then use the base class where you would want to use "const". Likewise, if you need to use "const" methods, add them to the base class. The compiler will not allow you to modify what it thinks is the final methods of the base class, but it will read and call methods on the subclass.
您可以使用 static Final 来创建类似于 Const 的东西,我过去曾使用过它。
You can use static final to create something that works similar to Const, I have used this in the past.
定义常量的方法有两种 -
const
和static final
,具有完全相同的语义。此外,static final
比const
更好地描述了行为There would be two ways to define constants -
const
andstatic final
, with the exact same semantics. Furthermorestatic final
describes the behaviour better thanconst