CSCI 200 Fall 2009

Laboratory 3 - Abstract Classes and Polymorphism

Goal

Learn how to use abstract classes and to see how polymorphism works in Java.

Grading

The lab exercise is worth 10 points. There are 4 points for part 1, 2 points for part 2, 2 points for part 3 and 2 points for part 4.

There is no design document for this lab.

Exercise Details

  1. Take one of your classes from homework 1 and make it abstract. It is to have a concrete toString method. It is to have an abstract printSubclass() method that will print out the instance variables in the concrete subclass. The toString() method in your superclass is to call the printSubclass() method. This method is abstract in your superclass, but concrete in each subclass that inherits from it.

    Create at least 3 subclasses inheriting from your abstract class. Create at least 2 instances of each of the 3 subclasses and store all of these objects into a single ArrayList. Then iterate through this ArrayList calling the printSubclass() method for each of the objects and have it print out the subclass information. Your ArrayList will hage at least 6 entries - 2 from each of your 3 subclasses.

    For example, if your superclass is called Card, then your ArrayList declaration would look like this:

        ArrayList<Card> cards = new ArrayList<Card>();
    

    Your subclasses will look like this:

    public class SubCard1 extends Card {
      public void printSubclass();
    
    //Rest of subclass code here
    }
    

    Show your TA that you actually get the subclass values printed out, even though you called the toString() method of your superclass.

  2. Change the abstract printSubclass method in the superclass to a concrete method and have it print out something unique for the superclass. Create 2 instances of the superclass and add it to your ArrayList from part 1. Call this method for all objects in the ArrayList. What printed out? Why did this happen?
  3. Change your code that iterates through the ArrayList so that you cast each object back to its original type. This means you are going to have an if/else if/else block using the instanceof operator to verify what each object type is, then do the actual cast inside that block. Call the printSubclass() method on each cast object. Does it change what gets printed out, or not? Why does it work that way?
  4. Now remove the printSubclass() method from your superclass completely. See what happens. Be able to answer the following questions: