Re: a question related to "final static" field variable
www wrote On 05/04/07 16:06,:
Patricia Shanahan wrote:
Make rootDir private and change it only once inside the class, from main.
If other classes need access you can provide a getRootDir() method,
which can check for attempts to read it before it has been set.
Patricia
Suppose my program has about 20 classes and the class with main method
is MyClass provided in my original posting. Suppose one class
"Worker.java" needs to know the root directory in order to read in the
text file. Right now, Worker does NOT have a MyClass in it. But, if I
follow your method, I need:
<inside Worker.java>
MyClass class = new MyClass();
String rootDir = class.getRootDir();
...//append rootDir in the front of text file name
</inside Worker.java>
I feel it is kind of silly that in order to get to know what the root
directory it is, Worker is forced to have a MyClass in it.
In the class as you wrote it, the only way MyClass
discovers where rootDir is supposed to be is by having
somebody, somewhere, create a MyClass object and pass
the value in as an argument to the constructor. If you
never construct a MyClass, nobody ever tells a constructor
what rootDir should be. What should MyClass do? Just
make something up out of thin air?
I'm not 100% sure what you're trying to do, but if
the idea is for MyClass to "remember" the first rootDir
from the construction of the first MyClass instance,
then you can't use a static final. Why? Because the
static field belongs to the class and not to the instance,
and must be initialized when the class is loaded and not
later on when instances are (or aren't) constructed.
What you might want to do instead is use a private
static variable and an accessor method, something like:
public class MyClass {
private static String rootDir;
public MyClass(String dir) {
if (rootDir == null) {
// first instance: initialize
rootDir = dir;
}
}
public string getRootDir() {
if (rootDir == null) {
// optional: could just return null
throw new IllegalStateException(...);
}
return rootDir;
}
}
--
Eric.Sosman@sun.com