java和C++的const 和 final 的区别

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的实例调用

java和C++的const 和 final 的区别
class Foo {
public:
   void bar();
   void foo() const;
};

void test(const Foo& i) {
   i.foo(); //fine
   i.bar(); //error
}
java和C++的const 和 final 的区别

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.

java和C++的const 和 final 的区别,布布扣,bubuko.com

java和C++的const 和 final 的区别

上一篇:NSIS脚本调用C语言写的插件


下一篇:使用 MVC 模式实现 JavaScript 树形结构