In C++ marking a member function const
means it may be called on
const
instances. Java does not have an equivalent to this
把一个类到成员函数标记为const表示它只能被const的实例调用
class Foo { public: void bar(); void foo() const; }; void test(const Foo& i) { i.foo(); //fine i.bar(); //error }
In Java the final keyword can be used for four things:
- on a class or method to seal it (no subclasses / overriding allowed)
- on a member variable to declare that is it can be set exactly once (I think this is what you are talking about)
- on a variable declared in a method, to make sure that it can be set exactly once
- on a method parameter, to declare that it cannot be modified within the method
One important thing is: A Java final member variable must be set exactly once! For example, in a constructor, field declaration, or intializer. (But you cannot set a final member variable in a method).
Another consequence of making a member variable final relates to the memory model, which is important if you work in a threaded environment.