Informatica Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Phone Interview
Final keyword guarantees that variable marked will not changed but in case of StringBuffer that is a reference which will never change. As mentioned above you can't assign a new object to it.
Agree with the last responses. Other option (overkilling?) may be to extend the class and override all the mutator fields. It wouldn't work in all cases (e.g, methods that change the state of the object and also return a value) but could be a solution for simple cases.
This requires you to be aware of the implementation of the class.
You can't declare that kind of constant in Java. There's no way to do it based on declarations alone.
In Java, when you use the "final" keyword, you only receive the rather weak guarantee that the variable marked as final will reference the same object throughout the variable's lifespan. It doesn't guarantee that the object being referenced won't have its state changed.
For example, to use the example of StringBuffer:
In other words, a final declaration locks a variable into referencing the same object for all time (well, until the variable goes out of scope and is no longer relevant). It does not, however, prevent the object itself from changing state. On the other hand, a non-final variable may, during its lifespan, reference different objects at different points in time.
- eugene.yarovoi June 15, 2012The way to make objects completely constant is to design classes with no mutator methods. If there's no way to alter the state of an object, the object is fixed once constructed. String is an example of a class that does this. If you now create a final String variable, you can neither assign another String to the variable nor modify the String already in the variable.