Solved

method argument as final

Posted on 2016-08-14
1
95 Views
Last Modified: 2016-08-14
Hi,

When do we need to declare method argument as final say as below

void addPerson(final Employee theEmployee) {
......
.....

}

please advise
0
Comment
Question by:gudii9
1 Comment
 
LVL 26

Accepted Solution

by:
dpearson earned 500 total points
ID: 41755845
>> When do we need to declare method argument as final say as below

You almost never have to declare arguments as final, but some people consider it good practice and it may be adopted as a coding standard by some companies.

The reason to do this is that "final" makes sure the parameter cannot be modified within the method, which keeps the logic simpler.

void addPerson(final Employee theEmployee) {
    ... stuff before
    process(theEmployee) ; // guaranteed that this is the employee that was passed in
}

Open in new window


Without final the value could change:
void addPerson(Employee theEmployee) {
    ... stuff before
    process(theEmployee) ; // maybe modified along the way
}

Open in new window


E.g. Here's how not making it final allows parameter to be changed:
void addPerson(Employee theEmployee) {
    ... stuff before
    theEmployee = anotherEmployee; 
    ... more stuff
    process(theEmployee) ; // may not be what was intended
}

Open in new window


So it's probably a good idea to usually add "final" to parameters to methods by default.
So why don't people do this more often?  Because it's extra typing.

Doug
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
session migration servlets 2 38
eclipse buid path vs tomcat lib path 10 24
Is there any way to convert exponential value to number in sql server 5 40
Help Required 3 97
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question