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:
- Define a class that inherits from another class.
- 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
- Start up Eclipse and create a new Java project called "Lab2".
- 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.
- Write a constructor for
Shape that
initializes both outlineColor and
fillColor.
- 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".
- Create a new derived class of Shape
called Rectangle that adds two new instance
variables, width and
height both of type int.
- Create a new derived class of Shape
called Circle that adds one new instance
variable, radius, of type
int.
- 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.
- 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
- Include your names as comments in your main class file.
- Package up your Lab2 directory (within your Eclipse workspace) as a .tar.gz file, e.g. by running tar cvfz lab2.tar.gz workspace/Lab2 on the command line (replace workspace/Lab2 as needed to point to your Lab2 directory).
- Submit the resultant archive to moodle.