Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final object in java [duplicate]

Tags:

java

Possible Duplicate:
When to use final

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

final Object obj = new myclass();
like image 216
Manu Avatar asked Jul 17 '10 11:07

Manu


People also ask

Can we clone final object in Java?

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.

What is duplicate object in Java?

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.

Does clone create new object in Java?

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.

Can objects be final in Java?

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).


1 Answers

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.

like image 56
S73417H Avatar answered Oct 13 '22 11:10

S73417H