Possible Duplicate:
When to use final
What is the use of declaring final
keyword for objects? For example:
final Object obj = new myclass();
The clone() method of Object class is used to clone an object. The java. lang. Cloneable interface must be implemented by the class whose object clone we want to create.
To summarize, duplicate objects, i.e. multiple instances of the same class with identical contents, can become a burden in a Java app. They may waste a lot of memory and/or increase the GC pressure. The best way to measure the impact of such objects is to obtain a heap dump and use a tool like JXRay to analyze it.
Clone() method in Java In Java, there is no operator to create a copy of an object. Unlike C++, in Java, if we use the assignment operator then it will create a copy of the reference variable and not the object.
In Java, we know that String objects are immutable means we can't change anything to the existing String objects. final means that you can't change the object's reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With