I'm in the middle of studying java programming and I'm a bit confused about constants. From what I've read so far constants are final and cannot be reassigned a new value unlike variables. However, when I'm using the Calender class there is the set method which seems to change a constant field. For example:
Calendar cal = Calendar.getInstance();
System.out.println("The year is " + cal.get(Calendar.YEAR));
cal.set(Calendar.YEAR, 2001);
System.out.println("The year is " + cal.get(Calendar.YEAR));
If the Calendar.YEAR
field is declared final
in the Calendar
class then why am I able to change it to another value using the set method?
Calendar.YEAR
is just a constant saying which logical field you want to set within the calendar.
The aim was to avoid having an API with
setYear
setDay
setMonth
...
In retrospect, I'd say this was a spectacularly bad idea - along with most of the rest of the design of java.util.Calendar
and java.util.Date
.
So this call:
cal.set(Calendar.YEAR, 2001)
doesn't change the value of Calendar.YEAR
... it changes some other (private) field within the Calendar
object.
See more on this question at Stackoverflow