Target in java

Possible duplicate:
When to use the final version

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

 final Object obj = new myclass(); 
+6
java
source share
4 answers

Using the final keyword means that the variable you declare is immutable. After the initial assignment, it cannot be reassigned.

However, this does not necessarily mean that the state of the instance referenced by the variable is unchanged, only the link itself.

There are several reasons why you would use the final keyword for variables. One of them is optimization, where, declaring a variable as final, the value is memoized .

Another scenario in which you must use the final variable is when the inner class inside the method needs to access the variable in the declaration 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 the need for a โ€œfinalโ€ is that the new instance of the class can survive the method call and therefore needs its own instance of x. To avoid having multiple copies of a variable to be modified 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 accidental redistribution of variables where they should not be. A rule type of best practice.

+21
source share

Final variables cannot be reassigned. If they are the scope of a class or instance, they must be assigned when the object is created. One use: constants that you don't want anyone else to use yours to change, for example. string or int constants (although enumerations make it better in 1.5+). In addition, if you want to refer to a region method variable from an anonymous method that you define inside this method, it must be final, so Java should not deal with what happens if your code reassigns this variable later, after it create a local stack / stack area for the internal anonymous method. It talked about incorporating some form of closure in Java 7 that could have avoided this limitation.

Maybe I messed up the terminology a bit - sorry! but what a general idea.

+6
source share

Another use of the finale to prevent it from being accidentally changed:

 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, because if == == 1, s will be assigned twice, due to the absence of a breakthrough. The final may help in the nasty switch statements.

+6
source share

It declares a variable that cannot be changed after initialization. Read-only sorting.

+3
source share

All Articles