Question about final instance variables

Hi, I recently have come across a situation that I realized I did not understand and I could not find the answer after a bit of googling and searching the forum so I thought I would quickly pose the question to the crowd. Basically I want to know if declaring a final instance variable and assigning it to an existing Object will make an immutable copy of that Object. For example:

...

Dimension myDims;

public void someMethod()

{

myDims = new Dimension(320, 240);

doSomething();

}

public void doSomething()

{

final myFinalDims = myDims;

}

...

This is not real code (obviously) and I made it quickly just to get my point across. Basically my question is if I create an Anonymous Inner class within the doSomething() method that accesses the myFinalDims variable, will the inner class actually access the myDims variable (which could have its value changed before the inner class accesses the variable) or will it be accessing a copy of the myDims Object that will have the same value as when the final variable was declared and instantiated?

[1133 byte] By [skyrunnera] at [2007-10-3 4:29:04]
# 1

> Basically I want to know if declaring

> a final instance variable and assigning it to an

> existing Object will make an immutable copy of that

> Object.

Big no. It will neither make a copy, nor will anything be immutable. Final just means that once the value or reference of the attribute or variable is set, it can't be altered.

final StringBuffer sb = new StringBuffer();

sb.append("!");

still works.

Your inner class will access the instance of Dimensions stored in myDims. There won't be any other instance.

CeciNEstPasUnProgrammeura at 2007-7-14 22:32:07 > top of Java-index,Java Essentials,Java Programming...
# 2
No.final Point p = new Point();p.x = 1; // this is legalp = new Point(); // not legal
tymer99a at 2007-7-14 22:32:07 > top of Java-index,Java Essentials,Java Programming...
# 3
The "final" keyword modifies the variable, not the object referenced by the variable.
paulcwa at 2007-7-14 22:32:07 > top of Java-index,Java Essentials,Java Programming...
# 4
Okay, thanks for the quick responses, you have cleared up all of the confusion that I had.
skyrunnera at 2007-7-14 22:32:07 > top of Java-index,Java Essentials,Java Programming...