Javatpoint Logo

what is the need of creating object as final

By: sabahu*** On: Tue Aug 12 13:34:48 IST 2014     Question Reputation0 Answer Reputation0 Quiz Belt Series Points0  0Blank User
like final Customer c=new Customer();Up0Down

 

If you make and object as a final then you can call any methods which do internal changes as usual,


because 'obj' is a reference to an object, and the real object is on the heap and the reference tells you
how to get there.
Image Created0Down

By: [email protected] On: Tue Aug 12 15:30:26 IST 2014 Question Reputation0 Answer Reputation392 Belt Series Points0 392User Image
Are You Satisfied :0Yes0No
 
Hi ravi. Thanks for your response. Can you elaborate it more with the help of an example?Image Created0Down

By: [email protected] On: Tue Aug 12 17:10:51 IST 2014 Question Reputation0 Answer Reputation0 Belt Series Points0 0User Image
Are You Satisfied :0Yes0No
 

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

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

public void go() {

final int x = 2;

new Runnable() {


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

};

}

If here you don't declared x as "final" the code will result in a compilation error.

the variable must be declared final.To avoid having multiple copies of a mutable variable within the same scope, so that it cannot be changed.

and

the use of "final" to prevent re-assigning variables accidentally.kind of a "best practice" type rule.

Image Created0Down

By: [email protected] On: Tue Aug 12 18:25:44 IST 2014 Question Reputation0 Answer Reputation392 Belt Series Points0 392User Image
Are You Satisfied :0Yes0No