Article View: borland.public.jbuilder.java.language
Article #14581How to make a "constant" object
From: Michael Drews
Date: Thu, 26 Aug 1999 00:00
Date: Thu, 26 Aug 1999 00:00
40 lines
1714 bytes
1714 bytes
I am fairly new to Java, having used C++ in the past. I would like to
know if there is a way (or what is the best way) to protect the data in
a Java object when needed. Consider the following class:
public class ABC
{
int iField = 0;
public ABC() {}
public setField(int i) { iField = i; }
}
In C++, I could declare a constant variable of class ABC:
const ABC abc = new ABC();
and then, if I tried either of the following statements, the compiler
would generate an error, since I was trying to change the constant
object or its data:
abc = new ABC(); // Error
abc.setField(2); // Error
In Java, if I declare a final variable, I can't change the object which
the variable references, but I can change the data in the referenced
object:
final ABC abc = new ABC();
abc = new ABC(); // Error
abc.setField(2); // This is allowed!
I want to be able to declare some sort of "final" or "constant" object
which does not allow its data to be modified. Is there any mechanism for
this in Java, or some accepted method for accomplishing this task?
Thanks in advance.
Mike Drews
Technical Details
Message-ID:
<37C5BCCC.8F102F85@pe-nelson.com>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailShow Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f74b3,99c34274d2b6c246,start X-Google-Attributes: gidf74b3,public From: Michael Drews <DrewsMA@pe-nelson.com> Subject: How to make a "constant" object Date: 1999/08/26 Message-ID: <37C5BCCC.8F102F85@pe-nelson.com> X-Deja-AN: 517616973 Content-Transfer-Encoding: 7bit Organization: Another Netscape Collabra Server User X-Accept-Language: en Content-Type: text/plain; charset=us-ascii Mime-Version: 1.0 Newsgroups: borland.public.jbuilder.java.language