Then how should one go about declaring constants in Java?
Fortunately, the final keyword can be applied to variables in addition to classes as well as methods. The use of final keyword on variables makes sure that the value of the variable can’t be changed.
public final int a = 2; a=3; //will flash compiler error
Once the final variable a has been initialized to 2, its value can’t be changed to 3.
But generally, constants are not associated to a particular instance of the class. So it is better to add static modifier also as:
public static final a = 2;
But wait there is a catch when using object references. Consider this:
public static final obj = new Object(); obj = new Object(); //compiler error as expected
The second line will make the compiler flash an error about changing the reference obj which was pointing to some other object.
But how about this:
public static final UserCar usrcar = new UserCar (“suzuki”); usrcar.changeTo(“honda”); // no compiler error
In the above case, no error is flashed by compiler because the final reference is still pointing to the same object as it was initialized. After second line, it’s the car object that has been modified and not the object reference “usrcar”.
So how would you go about making your object as final as opposed to object reference being final. Well, just make the object reference as “private” so that no other program can modify your object.