Subclass an existing class

Source code in Date.zip

  1. The Java files
    1. Date.java
    2. SmarterDate.java: the Java keywords extends, protected, and super; the annotation @Overrides.
    3. DateActivity.java
    4. R.java. Do not edit this file.
  2. The XML files
    1. main.xml
    2. strings.xml
    3. AndroidManifest.xml

Create the project

To allow the subclass SmarterDate to mention the length, year, month, day members of class Date, change them from private to protected in the file Date.java. Add class SmarterDate to the previous project.

File → New → Class
Package: edu.nyu.scps.date
Name: SmarterDate
✓ Constructors from superclass
✓ Inherited abstract methods
✓ Generate comments
Finish

The Package Explorer in the Java Perspective should now show three .java files:

▼ Project
  ▼ src
    ▼ edu.nyu.scps.project
      ► Date.java
      ► Project.java
      ► SmarterDate.java

Change the Date in DateActivity.java to a SmarterDate.

Run the project

The app now knows that February, 2011 has only 28 days. The call to next with no arguments moved the date to March 1. Then the call to next with one argument moved the date to March 11.

03-09 11:39:54.177: DEBUG/mytag(669): s == 3/11/2011
03-09 11:39:54.177: DEBUG/mytag(669): d == 3/11/2011

Things to try

  1. Create a subclass of SmarterDate named EvenSmarterDate. It should know about the two gaps in the calendar: the year 0 did not exist, and September 3–13, 1752 did not exist.
       September 1752
     S  M Tu  W Th  F  S
           1  2 14 15 16
    17 18 19 20 21 22 23
    24 25 26 27 28 29 30
    
    It should also know that before 1752, every fourth year was a leap year.