Patch: error->warning when assigning to final field

Mark Wielaard mark@klomp.org
Sun Jan 14 13:24:00 GMT 2001


Hi,

On Sun, Jan 14, 2001 at 09:48:36AM -0800, Per Bothner wrote:
> I checked in the following.  It changes an error to a warning when
> assigning to a final field outside an initializer.  An error is not
> appropriate, since assigning outside an initializer does not violate
> the JVM Spec, and Sun's verifier does not complain.  A warning *is*
> appropriate - for one thing MicroSoft's verifier *does* complain.

It does violate JLS 4.5.4, 8.3.1.2, 15.14.1/2, 15.15.1/2, 15.26 and
chapter 16 (see also the example in 6.5.6).

Some quotes from those sections:

  A variable can be declared final. A final variable may only be assigned
  to once. It is a compile time error if a final variable is assigned to
  unless it is definitely unassigned (§16) immediately prior to the
  assignment.

  A blank final instance variable must be definitely assigned (§16.8) at
  the end of every constructor (§8.8) of the class in which it is declared;
  otherwise a compile-time error occurs.

  (Post/Prefix inc/dec operations): A variable that is declared final
  cannot be incremented, because when an access of a final variable is
  used as an expression, the result is a value, not a variable. Thus,
  it cannot be used as the operand of a postfix increment operator.

  A variable that is declared final cannot be assigned to (unless it is
  a blank final variable (§4.5.4)), because when an access of a final
  variable is used as an expression, the result is a value, not a variable,
  and so it cannot be used as the first operand of an assignment operator.

  every blank final variable must be assigned at most once; it must be
  definitely unassigned  when an assignment to it occurs. A Java compiler
  must carry out a specific conservative flow analysis to make sure that,
  for every assignment to a blank final variable, the variable is
  definitely unassigned before the assignment; otherwise a compile-time
  error must occur.

It might also prevent some optimizations if final variables are suddenly
not really final. So I don't think it is a good idea to allow it because
the restriction isn't explicitly checked by some JVMs.

Cheers,

Mark


More information about the Java-patches mailing list