Why is there no Constant feature in Java?

后端 未结 8 1874
青春惊慌失措
青春惊慌失措 2020-11-28 02:20

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

8条回答
  •  一个人的身影
    2020-11-28 03:13

    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:

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

提交回复
热议问题