你好
方法/构造函数参数上的final修饰符有什么用?
例如:
class someClass {
private final double some; // I understand the use of final in this context, immutability etc..
public someClass(final double some) {
// I don't understand what purpose is served by making "some" final
this.some = some;
}
public void someMethod(final double some) {
// I don't understand what purpose is served by making "some" final
}
}发布于 2010-11-12 22:11:12
当你需要它的时候,有两种主要的情况:
1)您希望在本地类(通常是匿名类)中使用参数,如下所示:
public void foo(final String str) {
Printer p = new Printer() {
public void print() {
System.out.println(str);
}
};
p.print();
}2)当每个未修改的变量都用final单词标记时,您喜欢这种样式(通常情况下,让尽可能多的变量保持不变是一种好的做法)。
发布于 2010-11-12 22:05:17
这样做的目的是你不能给参数赋值任何东西。
public someClass(T some) {
some = null; //You can do this. Maybe you want to use the variable `some` later on in your constructor
}
public someClass(final T some) {
some = null; //You can't do this. If you want to reuse `some` you can't.
}有用吗?不是很多。通常你不会使用参数变量。但在某些特殊情况下,您可能希望能够做到这一点。
无论如何,如果某些函数执行了new someClass(mySome),那么mySome将永远不会改变,尽管在函数内部可以为参数赋值。在Java语言中没有pass-by-refrence这样的东西。变量是原语或对对象的引用,而不是对象本身。
发布于 2010-11-12 22:10:02
从函数的角度来看,某个变量是一个常量。
另一个好处是防止变量重用。这就是说,“一些”应该只用于一个目的。
https://stackoverflow.com/questions/4165407
复制相似问题