How to use predefined class constants (e.g. DAY_OF_WEEK in Calendar class)
Joined: Jan 23, 2009
I've managed to write a simple java app for reading a long table of ascii data where each line begins with the date. I then process each line of data depending on its day of the week.
I get the day of the week by using myCalendarObject.get(DAY_OF_WEEK) except that I had to use the integer 7 instead of DAY_OF_WEEK because the compiler doesn't know where to find the definition.
The way I figured out that 7 is the correct number is by calling a class method to fetch the value of DAY_OF_WEEK_FIELD.
Now, do I really need to use a class method to retrieve that value and assign it to a variable before I can use it?
Seems way too complicated to me.
Lee Kian Giap
Joined: Jan 23, 2008
In Java the only place you can access a field directly without go through Class or object is in the code of that Class.
In classes other than the class where the field declare, you need to either using ClassA.fieldname (for static field) or objectA.fieldname (for non-static field),
However, if you are using jdk1.5 or higher, to access the field directly you might achieve static import.
Now, refer to jdk api documentation, you will find out that DAY_OF_WEEK is a static field of class Calendar
so to access a static field, you need to do this Calendar.Day_OF_WEEK (you might access from Calendar object e.g. myCalendar.DAY_OF_WEEK, but this is not encourage)
as stated above by using static import, import static java.util.Calendar.*.