Overloaded Constructors


The Date class provides a handful of constructors. It is possible and often desirable to provide a developer with more than one way to construct new objects of a class type. You will learn how to create multiple constructors for your class in this lesson.

In the Date class, three of the constructors allow you to specify time parts (year, month, day, hour, minute, or second) in order to build a Date object for a specific date and time. A fourth constructor allows you to construct a date from an input String. A fifth constructor allows you to construct a date using the number milliseconds since the epoch. A final constructor, one that takes no parameters, constructs a timestamp that represents "now," the time at which the Date object was created.

There are also many methods that allow getting and setting of fields on the Date, such as setHour, setMinutes, getdate, and getSeconds.

The Date class was not designed to provide support for internationalized dates, however, so the designers of Java introduced the Calendar classes in J2SE 1.1. The intent was for the Calendar classes to supplement the Date class. The Calendar class provides the ability to work with dates by their constituent parts. This meant that the constructors and getters/setters in the Date class were no longer needed as of J2SE 1.1. The cleanest approach would have been for Sun to simply remove the offending constructors and methods.

However, if Sun were to have changed the Date class, large numbers of existing applications would have had to have been recoded, recompiled, retested, and redeployed. Sun chose to avoid this unhappy circumstance by instead deprecating the constructors and methods in Date. This means that the methods and constructors are still available for use, but the API developers are warning you that they will remove the deprecated code from the next major release of Java. If you browse the Date class in the API documentation, you will see that Sun has clearly marked the deprecated methods and constructors.

In this exercise, you will actually use the deprecated methods. You'll see that their use generates warnings from the compiler. Warnings are for the most part badthey indicate that you're doing something in code that you probably should not be. There's always a better way that does not generate a warning. As the exercise progresses, you will eliminate the warnings using an improved solution.

In the student information system, course sessions need to have a start and end date, marking the first and last days of class. You could provide both start and end dates to a CourseSession constructor, but you have been told that sessions are always 16 weeks (15 weeks of class, with a one-week break after week 7). With this information, you decide to design the CourseSession class so that users of the class need only supply the start dateyour class will calculate the end date.


Here's the test to be added to CourseSessionTest.

 public void testCourseDates() {    int year = 103;    int month = 0;    int date = 6;    Date startDate = new Date(year, month, date);    CourseSession session =       new CourseSession("ABCD", "200", startDate);    year = 103;    month = 3;    date = 25;    Date sixteenWeeksOut = new Date(year, month, date);    assertEquals(sixteenWeeksOut, session.getEndDate()); } 

You will need an import statement at the top of CourseSessionTest:

 import java.util.Date; 

This code uses one of the deprecated constructors for Date. Also of note are the odd-looking parameter values being passed to the Date constructor. Year 103? Month 0?

The API documentation, which should be your first reference for understanding a system library class, explains what to pass in for the parameters. Specifically, documentation for the Date constructor says that the first parameter represents "the year minus 1900," the second parameter represents "the month between 0 and 11," and the third parameter represents "the day of the month between 1-31." So new Date(103, 0, 6) would create a Date representation for January 6, 2003. Lovely.

Since the start date is so critical to the definition of a course session, you want the constructor to require the start date. The test method constructs a new CourseSession object, passing in a newly constructed Date object in addition to the department and course number. You will want to change the instantiation of CourseSession in the setUp method to use this modified constructor. But as an interim, incremental approach, you can instead supply an additional, overloaded constructor.

The test finally asserts that the session end date, returned by getEndDate, is April 25, 2003.

You will need to make the following changes to CourseSession in order to get the test to pass:

  • Add import statements for java.util.Date, java.util.Calendar, and java.util.GregorianCalendar;

  • add a getEndDate method that calculates and returns the appropriate session end date; and

  • add a new constructor that takes a starting date as a parameter.

The corresponding production code:

 package studentinfo; import java.util.ArrayList; import java.util.Date; import java.util.Calendar; import java.util.GregorianCalendar; class CourseSession {    private String department;    private String number;    private ArrayList<Student> students = new ArrayList<Student>();    private Date startDate;    CourseSession(String department, String number) {       this.department = department;       this.number = number;    }    CourseSession(String department, String number, Date startDate) {       this.department = department;       this.number = number;       this.startDate = startDate; } ... Date getEndDate() {       GregorianCalendar calendar = new GregorianCalendar();       calendar.setTime(startDate);       int numberOfDays = 16 * 7 - 3;       calendar.add(Calendar.DAY_OF_YEAR, numberOfDays);       Date endDate = calendar.getTime();       return endDate;    } } 

As I describe what getEndDate does, try to follow along in the J2SE API documentation for the classes GregorianCalendar and Calendar.

In getEndDate, you first construct a GregorianCalendar object. You then use the setTime[6] method to store the object representing the session start date in the calendar. Next, you create the local variable numberOfDays to represent the number of days to be added to the start date in order to come up with the end date. The appropriate number is calculated by multiplying 16 weeks by 7 days per week, then subtracting 3 days (since the last day of the session is on the Friday of the 16th week).

[6] Don't use this as a good example of method naming!

The next line:

 calendar.add(Calendar.DAY_OF_YEAR, numberOfDays); 

sends the add message to the calendar object. The add method in GregorianCalendar takes a field and an amount. You will have to look at the J2SE API documentation for Calendarin addition to the documentation for Gregorian-Calendarto fully understand how to use the add method. Gregorian-Calendar is a subclass of Calendar, which means that the way it works is tied tightly to Calendar. The field that represents the first parameter tells the calendar object what you are adding to. In this case, you want to add a number to the day of year. The Calendar class defines DAY_OF_YEAR as well as several other class constants that represent date parts, such as YEAR.

The calendar now contains a date that represents the end date of the course session. You extract this date from the calendar using the getTime method and finally return the end date of the course session as the result of the method.

You might wonder if the getEndDate method will work, then, when the start date is close to the end of the year. If that can possibly happen, it's time to write a test for it. However, the student information system you are writing is for a university that has been around for 200 years. No semester has ever begun in one year and ended in the next, and it will never happen. In short, you're not going to need to worry about it . . . yet.

The second constructor will be short-lived, but it served the purpose of allowing you to quickly get your new test to pass. You now want to remove the older constructor, since it doesn't initialize the session start date. To do so, you will need to modify the setUp method and testCourseDates. You should also amend the creation test to verify that the start date is getting stored properly.

 package studentinfo; import junit.framework.TestCase; import java.util.ArrayList; import java.util.Date; public class CourseSessionTest extends TestCase {    private CourseSession session;    private Date startDate;    public void setUp() {       int year = 103;       int month = 0;       int date = 6;       startDate = new Date(year, month, date);       session = new CourseSession("ENGL", "101", startDate);    }    public void testCreate() {       assertEquals("ENGL", session.getDepartment());       assertEquals("101", session.getNumber());       assertEquals(0, session.getNumberOfStudents());       assertEquals(startDate, session.getStartDate());    }    ...    public void testCourseDates() {       int year = 103;       int month = 3;       int date = 25;       Date sixteenWeeksOut = new Date(year, month, date);       assertEquals(sixteenWeeksOut, session.getEndDate());    } } 

You can now remove the older constructor from CourseSession. You'll also need to add the getStartDate method to CourseSession:

 class CourseSession {    ...    Date getStartDate() {       return startDate;    } } 



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net