What is the meaning of final keyword in java? I know that it is used to declare constant values which are not modifiable. But in the below program even I declare the vector as final, then still I am able to modify it? Can any body explain what is the scenario here?import java.util.*;public class A{ public static void main(String args[]) { final Vector v=new Vector(); v.addElement("element1"): }}

Questions by dvvn_sudha

Showing Answers 1 - 4 of 4 Answers

Rajesh

  • Apr 22nd, 2006
 

Hai UR QSTN is very good actually there v is the final object also called as immutable object these are the properties of immutable objects

Immutable objects carry some very desirable characteristics:

  • they are simple to understand and easy to use
  • they are inherently thread-safe: they require no synchronization
  • they make great building blocks for other objects

Clearly final is going to help us define immutable objects. First in labelling our object as immutable, which makes it simple to use and understand by other programmers. Second in guaranteeing that the object's state never changes, which enable the thread-safe property: thread concurrency issues are relevant when one thread can change data while another thread is reading the same data. Because an immutable object never changes its data, synchronizing access to it is not needed.

Create an immutable class by meeting all of the following conditions:

  1. Declare all fields private final.
  2. Set all fields in the constructor.
  3. Don't provide any methods that modify the state of the object; provide only getter methods (no setters).
  4. Declare the class final, so that no methods may be overridden.
  5. Ensure exclusive access to any mutable components, e.g. by returning copies.

  Was this answer useful?  Yes

Your question is good. But let me to explain what final key word will do. when you declare a variable as final you can't modify the varialbe for ever. When you declare a method as final you can't override the method. When you declare a class as final you can't inherit. In your above example you have declared the Vector class as final. Which means you can't inherit the class. But you can modify the class object. Thats what happening here...

gys.. Am i right or wrong? please let me know you can any conflict with this answer

  Was this answer useful?  Yes

jwala

  • May 2nd, 2006
 

You are extremely right.

  Was this answer useful?  Yes

wot my perception is when u declare this object reference as finalthis means that u can not change this reference, i mean u can not makethis final variable to point to another Vector object.e.g in same program i have difference Vector objectVector second = new Vector();then i can not do like this..v = second; // not legel~yogeshB

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions