Computer Science Canada

final?

Author:  matt271 [ Wed May 20, 2009 4:31 pm ]
Post subject:  final?

from my understanding, in java, final means constant.

like:

Java:
public static final String eh = "the";


but i tried to created a nested thread like this:

Java:
    public void test(final String eh) {
        new Thread() {
            @Override
            public void run() {
                System.out.println(eh);
            }
        }.start();
    }


and netbeans told me to "make String eh final" so i am curious what this final means in this case. how can it be a constant if its an argument?

public void test(final String eh) {

ty

Author:  Vermette [ Wed May 20, 2009 5:30 pm ]
Post subject:  Re: final?

Declaring method parameters to be final is a defensive programming strategy to help avoid unintended side effects. If the method has no need to modify a passed value, the final keyword prevents you from doing so.

Java:

//changing final values is illegal at compile time
public int foo(final int a) {
 
  //....
  return ++a;
}

//Changing final references is also illegal
public void bar(final SomeObj A) {

  SomeObj B = new SomeObj();
  //....
  A = B;
}

//however, manipulating objects is still legal
public void baz(final SomeObj B) {

  int x = 42;
  //....
  B.y = x;
}


Another thing to keep in mind is that using final does not alter the method signature when resolving a call, so foo(int a) and foo(final int a) are identical from an overloading perspective.

Author:  DemonWasp [ Wed May 20, 2009 6:48 pm ]
Post subject:  RE:final?

It's also worthy of note that in Java, the String class is final itself. That means that even though it's technically an object, you can't change it once it's created - all the mutator methods create a new String.

Author:  matt271 [ Wed May 20, 2009 11:44 pm ]
Post subject:  RE:final?

ok i get it. ty ty


: