Understanding Polymorphism via Inheritance

Recall that inheritance implies an is-a relationship between the base class and the derived class.

Consider the geometric figures given below, along with their informal descriptions:

Quadrilateral
four sided figure
Trapezoid
4 sides + one pair of parallel sides
Parallelogram
4 sides + both pairs of opposite sides parallel
Rectangle
parallelogram + 4 right angles
Square
parallelogram + all 4 sides congruent + 4 right angles
Rhombus
parallelogram + all 4 sides congruent
Isosceles Trapezoid
Trapezoid + non-parallel sides are congruent
Kite
quadrilateral + two pairs of distinct, adjacent sides are congruent + no two sides are parallel
  1. Organize these figures into an inheritance hierarchy. What problems, if any, would you encounter in implementing this hierarchy in Java?
  2. Write a class corresponding to each of the above figures using the inheritance hierarchy. In each class, include the following:
    1. a constructor that takes no arguments and prints a message of the form "Constructing a xxxxx'', when invoked.
    2. a method getName() that returns the geometric name, like "Square'', for that object.
    3. a method toString() that prints the description of the object when invoked. Can you reuse code in the inheritance hierarchy for this purpose?
  3. Write a small program to instantiate an object of each type and observe the order in which constructors are invoked when the object is instantiated.
  4. Assume each object created has a unique, numeric id, and a method getId() that returns this id. Add this functionality to your code.
  5. Assume you have a figure composed of these geometric shapes. You would like to save all the figures in a common data structure.
    1. Determine an appropriate data structure for this purpose.
    2. Create such a data structure and store the objects created in step 3 in this data structure.
    3. Use a for loop to run down this data structure and send each object the getId(), getName(), and toString() messages, printing the return value from each. What do you observe?

Email your zipped project folder as an attachment.


Based on Dr. Narayan's Lab 6 , Modified by Jack Tompkins