您的位置:首页 > 编程语言 > C语言/C++

java的修饰引用变量的final和C++的const区别真的很大

2016-08-16 00:00 609 查看
Bug ID: JDK-4211070 Java should support const parameters (like C++) for code maintainence http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4211070
A reference variable or constant declared as 'final'
has a value that is immutable and cannot be modified to
refer to any other object than the one it was
initialized to refer to.  Thus the 'final' specifier
applies to the value of the variable itself, and not to
the object referenced by the variable.

Only reference (non-primitive) types can have the
'const' specifier applied to them.  Primitive types
that need to be declared 'const' should be declared
'final' instead.

下面是自己写的一个关于java的final关键字的例子。可以说明上面的性质。

注意上面的性质只是针对reference variable,对于 Primitive types(基本数据类型),final关键字的意义和C++中的const是相同的。

疑问:

一、java中有没有什么方法可以实现类似C++中const对于函数返回引用类型时不可更改的限定效果??

二、C++中返回了const对象的引用,要将一个const对象引用赋值给一个非const引用是需要一定的技巧的。不能直接赋值。相关技术:指针,C++中的强制类型转换。由此可见const修饰只是让修改某个数据的限制增大,在C++中通过指针操作等,还是可以修改const变量的值的。难道这也是java中不使用const的原因??

三、在java中对于对象的引用的传递要时刻小心,尽可能减少直接传递对象的引用,而返回相应的数据域等。总之,遵循只传递方法完成功能所需的最少数据的原则。

class Base{
private int data;

public Base(int n){
this.data=n;
}
public boolean setData(int data){
this.data=data;
if(this.data==data) return true; //这样写真的好吗??
else return false;
}

public int getData(){
return this.data;
}

}
public class FinalKeyWordsTest{

public static void main(String[] args){
final Base base=new Base(12);
base.setData(13);
System.out.println(base.getData());

//错误: 无法为最终变量base分配值
//base=new Base(11); //can't do this on a final refernece varible.

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 关键字 final const