首页 > 编程语言 > 详细

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

时间:2014-03-14 18:37:37      阅读:596      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣
class Foo {
public:
   void bar();
   void foo() const;
};

void test(const Foo& i) {
   i.foo(); //fine
   i.bar(); //error
}
bubuko.com,布布扣

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 的区别

原文:http://www.cnblogs.com/Xiegg/p/3598942.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!