As Ajay already says, "final" does not make the object that the variable refers to unmodifiable. It just makes the variable itself unmodifiable, i.e. you can't change the value of the variable - but you can change the state of the object that the variable refers to.
There is no keyword in Java to do what you want to do.
One way to make clear that the Car instance shouldn't be mutated is introducing an interface that only contains the operations that don't mutate the car:
ReadonlyCar myCar = new Car();
or perhaps even better
Car myCar = new MutableCar();
How does that sound to you?
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Oct 12, 2006
Thanks for invoking such wonderful idea.
Your Theme sounds Excellent but could you please give me some more inputs on this?
I understand your idea like this:
1) Creating an interface "Car" that contains no mutators.
2) Then creating two concrete implementations such as "MutableCar" and "ImmutableCar" Am i Correct?
3) If so then how can i have the attributes?
This may be very silly question. But since i am not familiar with Design Pattern kind of stuffs, i need your help.
Originally posted by Jesper Young: Write a class Car that implements ReadonlyCar, and also has some extra methods that do allow you to modify the car.
You're proposing a mutable class which implements an interface with "Readonly" in its name. That doesn't sound very nice. Wherever possible the English names and ordinary meanings of classes should match their meanings in the program.
Sometimes, as code develops, one can't avoid some degradation of the natural meaning of class names, but one shouldn't design such confusion into the initial version.
What about "Readable" instead of "Readonly". If something is readable, that doesn't say anything about whether it can or cannot be written. [ January 16, 2007: Message edited by: Peter Chase ]
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.