我为什么要使用关键字“final”?在Java中的方法参数? [英] Why should I use the keyword "final" on a method parameter in Java?

查看:195
本文介绍了我为什么要使用关键字“final”?在Java中的方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在方法参数上使用时,我无法理解 final 关键字在哪里非常

I can't understand where the final keyword is really handy when it is used on method parameters.

如果我们排除使用匿名类,可读性和意图声明,那么对我来说似乎几乎一文不值。

If we exclude the usage of anonymous classes, readability and intent declaration then it seems almost worthless to me.

强制某些数据保持不变并不像看起来那么强大。

Enforcing that some data remains constant is not as strong as it seems.


  • 如果参数是基元,那么它将无效,因为参数作为值传递给方法并且正在改变它不会超出范围。

  • If the parameter is a primitive then it will have no effect since the parameter is passed to the method as a value and changing it will have no effect outside the scope.

如果我们通过引用传递一个参数,那么引用本身就是一个局部变量,如果引用是从方法中改变的,那就不会有来自方法范围之外的任何影响。

If we are passing a parameter by reference, then the reference itself is a local variable and if the reference is changed from within the method, that would not have any effect from outside of the method scope.

考虑下面的简单测试示例。
虽然方法改变了给它的引用值,但是这个测试通过了,它没有效果。

Consider the simple test example below. This test passes although the method changed the value of the reference given to it, it has no effect.

public void testNullify() {
    Collection<Integer> c  = new ArrayList<Integer>();      
    nullify(c);
    assertNotNull(c);       
    final Collection<Integer> c1 = c;
    assertTrue(c1.equals(c));
    change(c);
    assertTrue(c1.equals(c));
}

private void change(Collection<Integer> c) {
    c = new ArrayList<Integer>();
}

public void nullify(Collection<?> t) {
    t = null;
}


推荐答案

有时很高兴能够明确(为了便于阅读)变量不会改变。这是一个简单的例子,使用final可以节省一些可能的麻烦

Sometimes its nice to be explicit(for readability) that the variable doesn't change. Here's a simple example where using final can save some possible headaches

public void setTest(String test) {
    test = test;
}

如果您在设置器上忘记了'this'关键字您想要的变量设置没有设置。但是,如果您在参数上使用了final关键字,则会在编译时捕获该错误。

if you forget the 'this' keyword on a setter the variable you want to set doesn't get set. However if you used the final keyword on the parameter then the bug would be caught at compile time.

这篇关于我为什么要使用关键字“final”?在Java中的方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆