Once we write final
We can add, delete objects from this list, but I can not
So declaring the
There are two situations in which this can be useful.
ArrayList list = new ArrayList();
We can add, delete objects from this list, but I can not
list = new ArrayList() or list = list1.
So declaring the
list
final means that you cannot reassign the list
variable to another object.There are two situations in which this can be useful.
- You want to make sure that no-one reassigns your
list
variable once it has received its value. This can reduce complexity and helps in understanding the semantics of your class/method. In this case you are usually better off by using good naming conventions and reducing method length (the class/method is already too complex to be easily understood). - When using inner classes you need to declare variables as
final
in an enclosing scope so that you can access them in the inner class. This way, Java can copy yourfinal
variable into the inner class object (it will never change its value) and the inner class object does not need to worry what happens to the outer class object while the inner class object is alive and needs to access the value of that variable.
No comments:
Post a Comment