为什么 Java 中没有 Constant 功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2735736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:16:55  来源:igfitidea点击:

Why is there no Constant feature in Java?

javaconstantsfinal

提问by gmhk

I was trying to identify the reason behind constants in Java I have learned that Java allows us to declare constants by using finalkeyword.

我试图找出 Java 中常量背后的原因 我了解到 Java 允许我们通过使用final关键字来声明常量。

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 constkeyword.

我的问题是为什么 Java 没有引入 Constant ( const) 特性。因为很多人说它来自 C++,所以在 C++ 中我们有const关键字。

Please share your thoughts.

请分享您的想法。

采纳答案by Gunslinger47

Every time I go from heavy C++ coding to Java, it takes me a little while to adapt to the lack of const-correctnessin Java. This usage of constin 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.

每次我从繁重的 C++ 编码转到 Java 时,我都需要花一点时间来适应Java 中缺少常量正确性的问题。const如果您不知道,这种在 C++ 中的用法与仅声明常量变量有很大不同。本质上,它确保对象在通过一种称为常量指针的特殊指针访问时是不可变的。只包含不应有副作用的方法。不幸的是,这不是由语言强制执行的。

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.

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

回答by Bozho

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

将有两种定义常量的方法 -conststatic final,具有完全相同的语义。进一步static final描述行为比const

回答by Stephen C

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

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

The fact that constis 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 constwould cause compatibility problems.

const是一个保留词的事实表明设计者有实施的想法const,但他们后来决定反对;看到这个关闭的错误。所述原因包括添加对 C++ 样式的支持const会导致兼容性问题。

回答by Pete Kirkham

constin C++ does not mean that a value is a constant.

const在 C++ 中并不意味着一个值是一个常量。

constin C++ implies that the client of a contract undertakes not to alter its value.

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

Whether the value of a constexpression changes becomes more evident if you are in an environment which supports thread based concurrency.

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

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 finalhas.

由于 Java 从一开始就被设计为支持线程和锁并发,因此重载该术语以具有具有的语义并没有增加混淆final

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.

输出 42 然后是 7。

Although xmarked as const, as a non-const alias is created, xis not a constant. Not every compiler requires volatilefor this behaviour (though every compiler is permitted to inline the constant)

尽管x标记为const,因为创建了非常量别名,但x它不是常量。并非每个编译器都需要volatile这种行为(尽管每个编译器都被允许内联常量)

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. constmerely means that your code can't change it without a cast, not that the value is constant.

对于更复杂的系统,您可以在不使用 的情况下获得常量/非常量别名const_cast,因此养成认为 const 意味着某些东西不会改变的习惯变得越来越危险。const仅意味着您的代码无法在没有强制转换的情况下更改它,而不是该值是恒定的。

回答by Bert F

What does constmean
First, realize that the semantics of a "const" keyword means different things to different people:

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

  • read-only reference- Java finalsemantics - reference variable itself cannot be reassigned to point to another instance (memory location), but the instance itself is modifiable
  • readable-only reference- C constpointer/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?
  • 只读引用- Javafinal语义 - 不能重新分配引用变量本身以指向另一个实例(内存位置),但该实例本身是可修改的
  • 只读引用- Cconst指针/引用语义 - 意味着此引用不能用于修改实例(例如不能分配给实例变量,不能调用可变方法) - 仅影响引用变量,因此指向同一个实例可以修改实例
  • 不可变对象- 意味着实例本身不能被修改 - 适用于实例,因此任何非常量引用都不允许或不能用于修改实例
  • 以上的一些组合
  • 其他人

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:

为什么或为什么不const
第二,如果您真的想深入了解一些“赞成”与“反对”的论点,请参阅此增强请求 (RFE)“错误”下的讨论。此 RFE 请求“只读参考”类型的“const”功能。1999 年开放,然后在 2005 年被 Sun 关闭/拒绝,“const”话题引起了激烈的争论:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4211070

http://bugs.sun.com/bugdatabase/view_bug.do?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 constinclude:

虽然双方都有很多很好的论据,但一些经常被引用(但不一定令人信服或明确)的反对理由const包括:

  • may have confusing semantics that may be misused and/or abused (see the What does constmeanabove)
  • 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
  • 可能有混淆的语义,可能被误用和/或滥用(见什么const平均值以上)
  • 可能会复制其他可用的功能(例如设计一个不可变的类,使用一个不可变的接口)
  • 可能是功能蠕变,导致需要其他语义更改,例如支持按值传递对象


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 constkeyword may not be a good idea. Personally, I'd love more "const" semantics to be introduced to the language in an unambiguous manner.

在有人试图与我辩论这些是好的还是坏的理由之前,请注意这些不是我的理由。它们只是我从 RFE 讨论中收集到的一些原因的“要点”。我自己不一定同意他们的const观点- 我只是想说明为什么有些人(不是我)可能觉得某个关键字可能不是一个好主意。就我个人而言,我希望以明确的方式将更多的“const”语义引入到语言中。

回答by hamish

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

您可以使用 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;

回答by user1122069

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.

有一种方法可以在 Java 中创建“const”变量,但仅限于特定类。只需定义一个具有最终属性的类并将其子类化即可。然后在您想要使用“const”的地方使用基类。同样,如果您需要使用“const”方法,请将它们添加到基类中。编译器不允许你修改它认为是基类的最终方法,但它会读取和调用子类上的方法。

回答by grego

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.

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

This doesn't exactly answer why is there no const?but howto make your classes immutable. (Unfortunately I have not enough reputation yet to post as a comment to the accepted answer)

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

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 JavaItem 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".

这可以追溯到 Josh Bloch 的Effective Java Item 15 - Minimize Mutability。如果您还没有读过这本书,请拿起一本并多读几遍,我保证它会成为您比喻的“Java 游戏”

In item 15 Bloch suggest that you should limit the mutability of classes to ensure the object's state.

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

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.

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

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

Bloch 然后通过遵循 5 个简单规则描述了如何使您的类不可变:

  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)
  1. 不要提供任何修改对象状态的方法(即 setter,又名mutators
  2. 确保类不能被扩展(这意味着将类本身声明为final)。
  3. 制作所有字段final
  4. 制作所有字段private
  5. 确保对任何可变组件的独占访问。(通过制作对象的防御性副本)

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

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