Re: final and const java help needed for an old C++ programmer
- From: Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxxx>
- Date: Tue, 25 Sep 2007 08:26:10 -0400
apm35@xxxxxxxxxxxxxxxxxx wrote:
Hello,
I am relatively new to java but have been using C++ for ages. In C++ I
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. When the argument is an object
reference final just stops the reference being changed. You can still
alter the state of the object that the reference refers to. Also I
notice that final does not seem to get used much. I wonder why that
is....
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.
--
Eric Sosman
esosman@xxxxxxxxxxxxxxxxxxxx
.
- Follow-Ups:
- References:
- Prev by Date: Re: Exception in thread "main" java.lang.NoClassDefFoundError: TableDemo (wrong name: components/TableDemo)
- Next by Date: Re: final and const java help needed for an old C++ programmer
- Previous by thread: 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
|