You can't reassign a final member, can you?


A final interface or class member can only be assigned a value once, in the class or interface declaration. But in Java it can be easy to forget the difference between a reference value and the object being referenced. Consider the interface names below:

interface names {
  String num_names[] = new String[] { "zero", "one", "two", "three",
                                      "four", "five", "six", "seven",
                                      "eight", "nine" };
  public void pr();
}

In this interface a String array object is assigned to the interface member num_names. Since this member is declared in an interface it is final automatically, even though there is no explicit final declaration.

In the example below, class more_names implements the names interface.

class more_names implements names {

  public void set_two() {
    num_names[2] = "bogus";
  }

  public void pr() {
    for (int i = 0; i < num_names.length; i++) {
      System.out.println("num_names[" + i + "] = " + num_names[i] );
    }
  }

}


class Test {
  public static void main( String args[] ) {
    more_names n = new more_names();

    n.set_two();
    n.pr();
  }
}

This Java code compile without error. If it is executed it will print

num_names[0] = zero
num_names[1] = one
num_names[2] = bogus
num_names[3] = three
num_names[4] = four
num_names[5] = five
num_names[6] = six
num_names[7] = seven
num_names[8] = eight
num_names[9] = nine

Note that element two of the array has been changed from "two" to "bogus". If num_names is final how is this possible? Note that the reference variable is final, not the object assigned to it. So the object can be changed, but the reference variable cannot. The method below, reset, would be flagged with an error by the Java compiler, since the final variable is assigned a new object.


  public void reset() {
    num_names = new String[] { "ten", "eleven", "twelve" }; // illegal
  }

Ian Kaplan, March 30, 2000
Updated:


back to javacompilers.com (BPI) table of contents