将函数的参数声明为final:为什么以及何时需要它? [英] Declaring parameter of a function as final: why and when is it needed?

查看:275
本文介绍了将函数的参数声明为final:为什么以及何时需要它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过android教程(与多线程,循环程序和处理程序有关),我遇到了:

Going through a tutorial for android (related to multithreading, loopers and handlers), i came across this:

public synchronized void enqueueDownload(final DownloadTask task)

我的问题是:

  1. 何时以及为什么需要将函数的参数声明为final?
  2. 它特定于Java还是在其他语言(例如C/C ++)中存在类似的东西?

推荐答案

在Java中,这通常是 ,以便您可以访问匿名内部类中的参数-此类通常在Android中用于事件处理程序之类的.

In Java this is usually so that you can access the parameter within an anonymous inner class - which is often used in Android for event handlers and the like.

真正的含义是参数的值不能在方法中更改,但是用途通常用于匿名内部类...

The real meaning is that the parameter's value cannot be changed within the method, but the purpose is usually for anonymous inner classes...

public synchronized void enqueueDownload(final DownloadTask task) {
    SomethingHandler handler = new SomethingHandler() {
        @Override public void handleSomething() {
            // This would not compile if task were not final
            task.doSomething();
        }
    };
    // Use handler
}

这篇关于将函数的参数声明为final:为什么以及何时需要它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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