In the following code the set method changes the field values of Calendar class.
The field YEAR is declared static int YEAR. So why by creating two objects of Calendar class, the changes to one object will reflect to the other? Here this doesn’t happen.
I would ask you how Java developers have implemented this?
Calendar calendar = new GregorianCalendar();
Calendar cal = new GregorianCalendar(2011,9,13);
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.YEAR));
Calendar.YEARis a constant that is only used to name a field used by theCalendar. The value of that field is not static: it can and will vary between instances ofCalendar.Calendardefines a number of these field names for the different components of date and time, specifically to be used with get and set operations for the corresponding fields.Here’s the section in the javadoc for
Calendar.YEAR.As for the implementation, the
setandgetmethods are aware of these different field types, and change values in the instance based on the constant passed in. Think of it like a bigswitchstatement ingetorset, switching on all the field values.