Re: final and const java help needed for an old C++ programmer
- From: Lew <lew@xxxxxxxxxxxxx>
- Date: Tue, 25 Sep 2007 10:09:22 -0400
apm35@xxxxxxxxxxxxxxxxxx wrote:
try to write code that is const-correct but I do not know how to do
the same in java. Can anyone advise please? When I looked at this
initially it seemed like final might do what I want but that only
seems to work for fundamental types. ...
Eric Sosman wrote:
final != const
Not even "They differ in some subtle way known only by
language lawyers," but "They are not in any way alike." You
will only confuse yourself further if you try to understand
final as a variation on const. To put it another way,
Java != C++
.... and you will only get into trouble by trying to understand
one as a dialect of the other. Learn each language on its own
terms, with its own strengths and weaknesses, and you'll be much
better off.
On a variable declaration, final means "This variable cannot
be changed after initialization," and for member variables it
also means "... and initialization must occur during construction
or class loading." If you want an object whose state does not
change, shield its members from outside influence and don't write
mutator methods.
Joshua Bloch's excellent book /Effective Java/ goes into detail on final and immutable objects. Brian Goetz, et al., cover implications for threaded programs in /Java Concurrency in Practice/. There are subtleties as to access by (possibly anonymous) inner classes.
The JLS sets the rules in
<http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.12.4>
<http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.3.1.2>
<http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.3.3>
<http://java.sun.com/docs/books/jls/third_edition/html/binaryComp.html#13.4.2>
<http://java.sun.com/docs/books/jls/third_edition/html/binaryComp.html#13.4.9>
<http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.5>
In other words, every place the word "final" appears in the JLS table of contents.
--
Lew
.
- References:
- final and const java help needed for an old C++ programmer
- From: apm35
- Re: final and const java help needed for an old C++ programmer
- From: Eric Sosman
- final and const java help needed for an old C++ programmer
- Prev by Date: Re: final and const java help needed for an old C++ programmer
- Next by Date: Re: adding graphics to my web app
- Previous by thread: Re: final and const java help needed for an old C++ programmer
- Next by thread: Re: final and const java help needed for an old C++ programmer
- Index(es):
Relevant Pages
|