Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring parameter of a function as final: why and when is it needed?

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

public synchronized void enqueueDownload(final DownloadTask task)

My questions are:

  1. When and why is it needed to declare a parameter of a function as final?
  2. Is it specific to Java or does something similar exist in other languages such as C/C++?
like image 559
SpeedBirdNine Avatar asked Dec 09 '22 04:12

SpeedBirdNine


1 Answers

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
}
like image 155
Jon Skeet Avatar answered Dec 11 '22 16:12

Jon Skeet