你好
方法/构造函数参数的 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
    }
}

最佳答案

当您需要它时,有两种主要情况:

1)你想在本地类(通常是匿名类)中使用参数,例如:

public void foo(final String str) {
    Printer p = new Printer() {
        public void print() {
            System.out.println(str);
        }
    };
    p.print();
}

2)您喜欢每个未修改的变量都标有 final 字的样式(通常最好保持尽可能多的内容不可变)。

关于java - 方法/构造函数参数的最终修饰符有什么用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4165407/

10-15 19:02