[英]Using the final modifier with mutator methods
In C++ you could write 在C ++中你可以写
Int getX() const { return x; }
Is there an equivalent method structure in Java using final? Java中是否有使用final的等效方法结构?
What about passing const/ final modified arguments to methods? 将const / final修改的参数传递给方法怎么样?
Like this C++ code 喜欢这个C ++代码
void printX(const int x);
For the C++ example: 对于C ++示例:
void printX(const int x);
you can use final
modifier in method parameters to indicate the parameter can't be modified inside the method: 您可以在方法参数中使用
final
修饰符来指示在方法内部无法修改参数:
void printX(final int x) {
System.out.println(x);
x++; //compiler error since `x` is marked as final
}
Note that using final
modifier for object reference variables just means that the reference can't be modified, but its inner contents still can: 请注意,对对象引用变量使用
final
修饰符只是意味着无法修改引用,但其内部内容仍然可以:
class Foo {
int x = 0;
}
class Bar {
changeFoo(final Foo foo) {
foo.x = foo.x + 1; //allowed even if `foo` is marked as final
foo = new Foo(); //compiler error...
}
}
From SJuan76 comment for this code 来自SJuan76对此代码的评论
Int getX() const { return x; }
it tells that the class state is not modified when this method is called.
它告诉我们在调用此方法时不会修改类状态。
There's no way in Java to mark a method like this. 在Java中没有办法标记这样的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.