为什么Java中没有Constant特性?

发布于 2024-08-31 02:13:41 字数 183 浏览 4 评论 0原文

我试图找出 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

猫腻 2024-09-07 02:13:41

每次我从繁重的 C++ 编码转向 Java 时,我都会花一些时间来适应 的缺乏Java 中的 const 正确性。如果您不知道的话,C++ 中 const 的用法与声明常量变量有很大不同。本质上,它确保对象在通过一种称为 const 指针的特殊指针访问时是不可变的。在 Java 中,在我通常想要返回 const 指针的地方,我会返回一个带有接口类型的引用仅包含不应该有副作用的方法。不幸的是,这不是由语言强制执行的。

维基百科提供了有关该主题的以下信息:

有趣的是,Java 语言规范将 const 视为保留关键字(即不能用作变量标识符的关键字),但没有为其分配任何语义。人们认为保留该关键字是为了允许 Java 语言的扩展,以包括 C++ 风格的 const 方法和指向 const 类型的指针。 Java 社区进程中用于在 Java 中实现 const 正确性的增强请求票已于 2005 年关闭,这意味着 const 正确性可能永远不会进入官方 Java 规范。

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:

Interestingly, the Java language specification regards const as a reserved keyword — i.e., one that cannot be used as variable identifier — but assigns no semantics to it. It is thought that the reservation of the keyword occurred to allow for an extension of the Java language to include C++-style const methods and pointer to const type. The enhancement request ticket in the Java Community Process for implementing const correctness in Java was closed in 2005, implying that const correctness will probably never find its way into the official Java specification.

今天小雨转甜 2024-09-07 02:13:41

const 是什么意思
首先,认识到“const”关键字的语义对不同的人意味着不同的东西:

  • 只读引用 - Java final 语义 - 引用变量本身不能重新分配给点到另一个实例(内存位置),但实例本身是可修改的
  • 只读引用 - C 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 mean
First, realize that the semantics of a "const" keyword means different things to different people:

  • read-only reference - Java final semantics - reference variable itself cannot be reassigned to point to another instance (memory location), but the instance itself is modifiable
  • readable-only reference - C const 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 instance
  • immutable object - means the instance itself cannot be modified - applies to instance, so any non-const reference would not be allowed or could not be used to modify the instance
  • some combination of the the above?
  • others?

Why 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:

  • may have confusing semantics that may be misused and/or abused (see the What does const mean above)
  • may duplicate capability otherwise available (e.g. designing an immutable class, using an immutable interface)
  • may be feature creep, leading to a need for other semantic changes such as support for passing objects by value

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.

七度光 2024-09-07 02:13:41

C++ 中的 const 并不意味着值是常量。

C++ 中的 const 意味着合约的客户端承诺不改变其值。

如果您处于支持基于线程的并发性的环境中,const 表达式的值是否发生变化会变得更加明显。

由于 Java 从一开始就被设计为支持线程和锁并发,因此它并没有通过重载该术语来获得 final 所具有的语义来增加混乱。

例如:

#include <iostream>

int main ()
{
    volatile const int x = 42;

    std::cout << x << std::endl;

    *const_cast<int*>(&x) = 7;

    std::cout << x << std::endl;

    return 0;
}

输出 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:

#include <iostream>

int main ()
{
    volatile const int x = 42;

    std::cout << x << std::endl;

    *const_cast<int*>(&x) = 7;

    std::cout << x << std::endl;

    return 0;
}

outputs 42 then 7.

Although x marked as const, as a non-const alias is created, x is not a constant. Not every compiler requires volatile 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.

世界和平 2024-09-07 02:13:41

这是一个有点老的问题,但我想无论如何我都会贡献我的 2 美分,因为今天的对话中出现了这个话题。

这并不能完全回答为什么没有 const?,而是如何让你的类不可变。 (不幸的是,我还没有足够的声誉来发布对已接受答案的评论)

保证对象不变性的方法是更仔细地设计你的类以使其不可变。这比可变类需要更多的关注。

这可以追溯到 Josh Bloch 的Effective Java项目 15 - 最小化可变性。如果您还没有读过这本书,请拿起一本并读几遍,我保证它将增强您的比喻“java游戏”

在第 15 项中,Bloch 建议您应该限制类的可变性以确保对象的状态。

直接引用这本书:

不可变类就是其实例无法修改的类。每个实例中包含的所有信息都是在创建实例时提供的,并且在对象的生命周期内是固定的。 Java 平台库包含许多不可变类,包括 String、装箱原始类以及 BigInteger 和 BigDecimal。这样做有很多充分的理由:不可变类比可变类更容易设计、实现和使用。它们不太容易出错并且更安全。

然后,Bloch 描述了如何通过以下 5 个简单规则使类不可变:

  1. 不要提供任何修改对象状态的方法(即 setters,又名mutators
  2. 确保类不能被修改。扩展(这意味着将类本身声明为final)。
  3. 将所有字段设为最终
  4. 将所有字段设为私有
  5. 确保对任何可变组件的独占访问。 (通过制作物体的防御性副本)

有关更多详细信息,我强烈建议您拿起这本书的副本。

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:

An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object. The Java platform libraries contain many immutable classes, including String, the boxed primitive classes, and BigInte- ger and BigDecimal. There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure.

Bloch then describes how to make your classes immutable, by following 5 simple rules:

  1. Don’t provide any methods that modify the object’s state (i.e., setters, aka mutators)
  2. Ensure that the class can’t be extended (this means declaring the class itself as final).
  3. Make all fields final.
  4. Make all fields private.
  5. Ensure exclusive access to any mutable components. (by making defensive copies of the objects)

For more details I highly recommend picking up a copy of the book.

囍笑 2024-09-07 02:13:41

C++ 的 const 语义与 Java final 非常不同。如果设计者使用const,那就会造成不必要的混乱。

const 是一个保留字,这一事实表明设计者曾有实现 const 的想法,但后来他们决定不这样做;请参阅此已关闭的错误。所述原因包括添加对 C++ 风格 const 的支持会导致兼容性问题。

The C++ semantics of const are very different from Java final. If the designers had used const it would have been unnecessarily confusing.

The fact that const is a reserved word suggests that the designers had ideas for implementing const, but they have since decided against it; see this closed bug. The stated reasons include that adding support for C++ style const would cause compatibility problems.

音盲 2024-09-07 02:13:41

根据我引用的一本教科书的说法,
“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"

白首有我共你 2024-09-07 02:13:41

有一种方法可以在 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.

春花秋月 2024-09-07 02:13:41

您可以使用 static Final 来创建类似于 Const 的东西,我过去曾使用过它。

protected static final int cOTHER = 0;
protected static final int cRPM = 1;
protected static final int cSPEED = 2;
protected static final int cTPS = 3;
protected int DataItemEnum = 0;

public static final int INVALID_PIN = -1;
public static final int LED_PIN = 0;

You can use static final to create something that works similar to Const, I have used this in the past.

protected static final int cOTHER = 0;
protected static final int cRPM = 1;
protected static final int cSPEED = 2;
protected static final int cTPS = 3;
protected int DataItemEnum = 0;

public static final int INVALID_PIN = -1;
public static final int LED_PIN = 0;
撩动你心 2024-09-07 02:13:41

定义常量的方法有两种 - conststatic final,具有完全相同的语义。此外,static finalconst 更好地描述了行为

There would be two ways to define constants - const and static final, with the exact same semantics. Furthermore static final describes the behaviour better than const

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文