Why is there no Constant feature in Java?

后端 未结 8 1790
青春惊慌失措
青春惊慌失措 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:18

    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.

    0 讨论(0)
  • 2020-11-28 03:20

    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.

    0 讨论(0)
提交回复
热议问题