Why is there no Constant feature in Java?

后端 未结 8 1856
青春惊慌失措
青春惊慌失措 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: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 
    
    int main ()
    {
        volatile const int x = 42;
    
        std::cout << x << std::endl;
    
        *const_cast(&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.

提交回复
热议问题