Re: public static final - compilation error
- From: Chris Smith <cdsmith@xxxxxxx>
- Date: Tue, 28 Jun 2005 10:17:20 -0600
Thomas Fritsch <i.dont.like.spam@xxxxxxxxxxx> wrote:
> No, you can't initialize 'static final' things in a constructor or any
> non-static method. But you can (and probably want to) initialize them in
> the class initializer:
>
> static
> {
> for (int i = 0; i < OPERATORY.length; i ++)
> {
> if(OPERATORY[i].equals("+")) PLUS = i;
> if(OPERATORY[i].equals("-")) MINUS = i;
> if(OPERATORY[i].equals("*")) MULTI = i;
> if(OPERATORY[i].equals("/")) DIVIDE = i;
> }
> }
>
> Hence, there is no need for your constructor anymore.
Unfortunately, this still does not work. The variables PLUS, MINUS,
MULTI, and DIVIDE are blank finals, and there are two rules that apply
here:
1. They must be guaranteed to be initialized by the time static
initialization is complete.
2. They must not be multiply assigned.
Both rules are applied according to the compiler's conservative
data/control flow analysis, as specified in the JLS. The actual
contents of the array are not considered in performing that analysis.
So the loop through the OPERATORY array is not a valid way of
accomplishing the initialization.
It's trivial to modify this code to use temporary variables, in order to
work around both restrictions on the direct use of finals. Here is the
result:
public class Stale
{
public static final String[] OPERATORS = new String[] {
"+", "-", "*", "/"
};
public final static int PLUS;
public final static int MULTI;
public final static int MINUS;
public final static int DIVIDE;
static
{
int plus = -1, minus = -1, multi = -1, divide = -1;
for (int i = 0; i < OPERATORS.length; i++)
{
if (OPERATORS[i].equals("+")) plus = i;
if (OPERATORS[i].equals("-")) minus = i;
if (OPERATORS[i].equals("*")) multi = i;
if (OPERATORS[i].equals("/")) divide = i;
}
assert plus != -1;
assert minus != -1;
assert multi != -1;
assert divide != -1;
PLUS = plus;
MINUS = plus;
MULTI = plus;
DIVIDE = plus;
}
}
(Incidentally, I also removed the pointless use of "new String", and
fixed the apparent typo with the array name.)
--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
.
- Follow-Ups:
- Re: public static final - compilation error
- From: Chris Smith
- Re: public static final - compilation error
- References:
- public static final - compilation error
- From: Kamil Roman
- Re: public static final - compilation error
- From: Thomas Fritsch
- public static final - compilation error
- Prev by Date: Re: public static final - compilation error
- Next by Date: Re: public static final - compilation error
- Previous by thread: Re: public static final - compilation error
- Next by thread: Re: public static final - compilation error
- Index(es):
Relevant Pages
|