开发者

final object in java [duplicate]

This question 开发者_开发百科already has answers here: Closed 12 years ago.

Possible Duplicate:

When to use final

What is the use of declaring final keyword for objects? For example:

final Object obj = new myclass();


Using the "final" keyword makes the the variable you are declaring immutable. Once initially assigned it cannot be re-assigned.

However, this does not necessarily mean the state of the instance being referred to by the variable is immutable, only the reference itself.

There are several reasons why you would use the "final" keyword on variables. One is optimization where by declaring a variable as final allows the value to be memoized.

Another scenario where you would use a final variable is when an inner class within a method needs to access a variable in the declaring method. The following code illustrates this:

public void foo() {

        final int x = 1;

        new Runnable() {


            @Override
            public void run() {
                int i = x;
            }

        };

}

If x is not declared as "final" the code will result in a compilation error. The exact reason for needing to be "final" is because the new class instance can outlive the method invocation and hence needs its own instance of x. So as to avoid having multiple copies of a mutable variable within the same scope, the variable must be declared final so that it cannot be changed.

Some programmers also advocate the use of "final" to prevent re-assigning variables accidentally where they should not be. Sort of a "best practice" type rule.


Another use of final to prevent accidentally changing it:

public String foo(int a) {
  final String s;
  switch(a) {
  case 0:
    s="zero";
    break;
  case 1:
    s="one";
    //forgot break;
  default:
    s="some number";
  }
  return s;
}

This will not compile since if a==1, s would be assigned twice, because of the missing break. Final can help in nasty switch statements.


Final variables cannot be reassigned. If they're class- or instance-scope, they must be assigned when an object is constructed. One use: constants you don't want anyone else using your to change, e.g. string or int constants (though enums do this better in 1.5+). Also, if you want to reference a method-scope variable from an anonymous method you define inside that method, it must be final, so Java doesn't have to deal with what would happen if your code reassigned that variable later, after it created the local stack frame/scope for the internal anonymous method. There's talk of including some form of closure in Java 7 which might avoid this restriction.

I may have botched the terminology a bit -- sorry! but that's the general idea.


It declares a variable that cannot be modified once initialized. Sort of readonly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜