final keyword in method parameters

This question already has an answer here:

  • Why should I use the keyword “final” on a method parameter in Java? 12 answers

  • Java always makes a copy of parameters before sending them to methods. This means the final doesn't mean any difference for the calling code. This only means that inside the method the variables can not be reassigned. (note that if you have a final object, you can still change the attributes of the object).


    There is a circumstance where you're required to declare it final --otherwise it will result in compile error--, namely passing them through into anonymous classes. Basic example:

    public FileFilter createFileExtensionFilter(final String extension) {
        FileFilter fileFilter = new FileFilter() {
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(extension);
            }
        };
    
        // What would happen when it's allowed to change extension here?
        // extension = "foo";
    
        return fileFilter;
    }
    

    Removing the final modifier would result in compile error, because it isn't guaranteed anymore that the value is a runtime constant. Changing the value from outside the anonymous class would namely cause the anonymous class instance to behave different after the moment of creation.


    Java is only pass-by-value. (or better - pass-reference-by-value)

    So the passed argument and the argument within the method are two different handlers pointing to the same object (value).

    Therefore if you change the state of the object, it is reflected to every other variable that's referencing it. But if you re-assign a new object (value) to the argument, then other variables pointing to this object (value) do not get re-assigned.

    链接地址: http://www.djcxy.com/p/20850.html

    上一篇: 在Java中使用final关键字可以提高性能吗?

    下一篇: 方法参数中的最终关键字