Lab 2: Inheritance, up-casts and down-casts in Java

Reading

Thinking in Java, Chapter 6 (up-to but not including "The Final Keyword")

Background


Inheritance and up-casts/down-casts are two of the four key components of object oriented languages (the other two are "classes" which we covered last week, and dynamic binding which we will cover in two weeks).  Inheritance enables you to create a new class that "extends" an existing class.  If class S inherits from class T, then S is called a subclass (or derived class) of T and T is called a superclass (or base class) of S.  S has all the instance variables and methods of T plus possibly some more.  After this lab you should know how to:

  1. Define a class that inherits from another class.
  2. Convert from superclass to subclass (down-cast) and from subclass to superclass (up-cast).  You should understand that up-casts always succeed but down-casts may or may not succeed.

Tasks

  1. Start up Eclipse and create a new Java project called "Lab2".
  2. Create a new Java class Shape which has the instance variables outlineColor (of type String), fillColor (of type String), and method draw (takes no arguments and returns void).  The method draw simply prints out the values of the two colors.  
  3. Write a constructor for Shape that initializes both outlineColor and fillColor
  4. Create a new class Driver with a main method which creates an array of Shape and puts two Shape objects in the array.  It then calls a function doIterate on the array.   doIterate (which is a method of Driver that you need to write) should walk over its argument array and invokes draw on all the shapes that have the outline color "Red"
  5. Create a new derived class of Shape called Rectangle that adds two new instance variables, width and height both of type int.
  6. Create a new derived class of Shape called Circle that adds one new instance variable, radius, of type int.
  7. Put instances of Circle and Rectangle in your array.  Note that the array is declared to hold Shapes yet you can still store Circle and Rectangle instances in it.  In comments in your code indicate if putting Circle and Rectangle in the array is an up-cast or a down-cast and why.  Invoke doIteration on this array; note how doIteration accesses elements in the array without worrying about whether or not the element is a Rectangle or a Circle.
  8. Write code (in the main method of the Driver class) that extracts elements from the array and converts these elements to their actual class (Circle, Rectangle, or Shape).  What happens if you do an incorrect conversion (e.g., you attempt to convert a Circle object to a Rectangle).

Deliverables