Reputation: 5664
We have a method whose parameter is defined as final,and then change the value of this parameter(in this method) and return it, it should not be changed as we passed it as final.
But this is not the case.
Please help me to understand this!
public static void main(String[] args) {
EmployeeBean e1 = new EmployeeBean("1", "jitu");
System.out.println("object before set >>" + e1.getEmpName());
EmployeeBean newObj = x.changeFinalvalue(e1);
System.out.println("object after set >>" + newObj.getEmpName());
public EmployeeBean changeFinalvalue(final EmployeeBean x) {
x.setEmpName("Jeet");
return x;
}
Output : object after set >>jitu
object after set >>Jeet //doubt:it has to be 'jitu' only
Upvotes: 2
Views: 386
Reputation: 285405
You are not changing which object is being referred to by the parameter (which is not allowed here). Instead you are changing the state of the object (which is allowed here).
In other words, when you pass your e1 EmployeeBean object into the method, the x parameter refers to the same object that e1 refers to, and within the method, this cannot change, and so you can't do this:
public EmployeeBean changeFinalvalue(final EmployeeBean x) {
x = new EmployeeBean(); // changing the reference is not allowed!
return x;
}
But what you're doing -- changing the state of the object -- is allowed.
The only way that I know to prevent problems like this is to make a deep copy of the object passed in as parameter and work on the copy/clone object. You could also make the EmployeeBean immutable, but then it wouldn't be much of a Bean, now would it?
Edit: I figured that this question has had to have been asked here many times, and on a little searching, I've found that of course it has. Please look at these links for a good discussion on this. Note that this is a general issue about final variables whether they are method parameters or class fields:
java-final-keyword-for-variables
java-final-modifier
Upvotes: 2
Reputation: 236114
The final
keyword in the parameter declaration part of a method means that you can't reassign it inside the method (say, x = new EmployeeBean();
). But clearly, you can change its attributes, and because the method receives a reference to the object, any changes you make to the object's state inside the method will prevail after the method returns to its caller.
The only way to ensure that it doesn't get modified is by making it immutable, but of course whether or not you can make a particular object immutable depends completely on the problem at hand.
Upvotes: 0
Reputation: 2295
The reason this works is because 'final' only makes sure that the parameter value is not changed. In this case, that means the reference to the object. The fields of the object can still change.
The same is true for all other final variables.
Upvotes: 1