CS 112
Spring 2018

Old version

This is the CS 112 site as it appeared on May 11, 2018.

Lab 3: Inheritance and polymorphism; the ArrayBag class

FLR 267

If your lab meets in FLR 267, you should begin by following the instructions found here.

Task 1: Understand and use inheritance

As we saw today in lecture, a class can extend another class. Consider the Animal and Cat classes in the following Java source code files:

Save these classes, open them in DrJava, and take note of how they are related.

Note: The Cat class will not compile until we first make some changes to it, so don’t try to compile anything yet!

  1. Which class is the superclass? Which is the subclass? What does it mean that the Cat class extends the Animal class?

  2. The Cat class cannot directly access the fields it inherits from Animal. Why not?

  3. The subclass constructor typically calls the superclass constructor to initialize the inherited fields. Write a constructor for the Cat class above. It should take as parameters the cat’s name and a boolean indicating whether it is short-haired, and it should call the superclass constructor to initialize the inherited fields.

  4. To manipulate the inherited fields, the subclass can use the inherited accessor and mutator methods. Write a toString method for the Cat class above. It should return a string consisting of the cat’s name followed by either " (short-haired)" or " (long-haired)".

  5. The subclass can override an inherited method, replacing it with a version that is more appropriate. Write an isSleeping method for the Cat class. It should reflect the fact that cats seem to sleep all of the time!

  6. Let’s say that we now want to define a class called Abyssinian for cats that belong to that particular breed of short-haired cat. Which class should it extend?

  7. Go ahead and create a class named Abyssinian in DrJava, defining it so that it extends the correct class. It should not have any new fields of its own. However, it should include:

    • a constructor that takes only a name, and that calls the superclass constructor to initialize the inherited fields. When making that call, make sure that it reflects the fact that Abyssinians are short-haired.

    • an isExtroverted() method that overrides the inherited version and replaces it with one that reflects the fact that Abyssinian cats are known to be extroverted.

  8. Another possible class for this hierarchy of animals is the Dog class, which you should examine now, although you don’t need to open it in DrJava. In addition to its inherited fields and methods, it has a boolean field isSmall, and methods isSmall() and bark().

  9. Let’s say that we have created an Abyssinian object and assigned it to the variable a:

    Abyssinian a = new Abyssinian("Abby");
    

    For each of the following method calls:

    • Indicate whether it will compile. Because the variable a is declared to be of type Abyssinian, a method call using a will compile if there is a corresponding method inside Abyssinian objects – either defined in the Abyssinian class itself or inherited from a superclass. A method call will not compile if there is no corresponding method in objects of that class.

    • If the method call will compile, specify which version of the method will be called. In other words, in which class can we find the version of the method that will be called?

    Here are the calls:

    1.     a.getNumLegs()

    2.     a.isExtroverted()

    3.     a.isSleeping(12, 30)

    4.     a.isSmall()

    5.     a.toString()

    6.     a.equals(a)

Task 2: Understand polymorphism

Your work for this task should go on the piece of paper that we give you. Please show your paper to a staff member before you leave the lab.

Thanks to a feature of Java called polymorphism, we can do something like this:

ClassA myObject = new ClassB(...);

Where ClassB extends ClassA, or equivalently, ClassB is a subclass of ClassA. Specifying a more general type for myObject than the actual type of the object can be useful when writing a method that needs to take more than one type of object as a parameter, or when creating an array of objects of different but related types.

For example, if we wanted to have an array containing different types of animal objects, we could define the array as follows:

Animal[] zoo = new Animal[10];

Then, any element of the array could be of type Animal or any subclass of Animal. In other words, this would be allowed:

zoo[0] = new Dog(...);
zoo[1] = new Cat(...);
zoo[2] = new Abyssinian(...);

Consider the following class headers:

public class A extends B {
    ...
}

public class B extends C {
    ...
}

public class C {
    ...
}

public class D extends C {
    ...
}
  1. Draw an inheritance hierarchy for these classes.

  2. Which of these assignments would be allowed, taking into account the rules of polymorphism?

    1.       B myObj = new A();
    2.       B myObj = new C();
    3.       C myObj = new A();
    4.       A myObj = new B();
    5.       D myObj = new B();

Task 3: Memory diagrams and the ArrayBag class

Some of your work for this task will go on the same piece of paper as your work for Task 2.

Let’s take a closer look at the ArrayBag class from lecture, which you will be modifying in Problem Set 3.

Recall that this class is one possible implementation of a data structure known as a bag, which is a simple collection of items in which the order of the items doesn’t matter. A good analogy is a bag of candy!

  1. What are the fields of the ArrayBag class, and why did we include them in our definition?

  2. Note that there isn’t a getItem() method for accessing a specific item in the bag. Instead, there is a method called grab() which accesses a random item in the bag. Why does this make sense, given the characteristics of a bag?

  3. In lecture, we looked at the add() method, which adds a single item to the ArrayBag. Let’s draw a memory diagram (stack and heap) of an ArrayBag object called b as the add() method is called on it for the first time. Show the addition of the string "don't blink"

  4. Open ArrayBag.java in DrJava and compile the class.

  5. Now use the Interactions Pane to do the following:

    • complete the following statement to create an ArrayBag object with the default maximum size:

      > ArrayBag b = ...
      
    • add "don't blink" to that ArrayBag

    • add "baggy" to that ArrayBag
  6. After performing these operations, see what your ArrayBag looks like by simply entering the variable from the prompt:

    > b
    {don't blink, baggy}
    

    Note that the Interactions Pane is calling the toString() method of the ArrayBag class, and that method produces the string that is displayed when b is evaluated.

  7. Let’s say that we now want to “grab” one of the items that we just added to b. What happens when you do the following?

    > String s = b.grab();
    

    Why does what you see make sense in light of the rules of polymorphism?

  8. We can make this work by using an operation known as a type cast:

    > String s = (String)b.grab();
    

    This doesn’t actually change the type of the underlying object. It just reassures the compiler that the assignment will be valid. If the item being returned were not a String object, an exception would be thrown.

  9. Add a non-static method called hasMoreRoom() that takes as a parameter another ArrayBag called other, and that returns true if the called ArrayBag has more room left for items (i.e., more unused array elements) than other does, and false otherwise.

    If other is null, the method should throw an IllegalArgumentException.

    For example:

    > ArrayBag b1 = new ArrayBag(10);
    > ArrayBag b2 = new ArrayBag(12);
    > b2.hasMoreRoom(b1)
    true
    > b2.add("hello");
    > b2.add("world");
    > b2.hasMoreRoom(b1)
    false
    

    Hint: Because this method is part of the ArrayBag class, it can directly access the private fields of the ArrayBag that is passed in as a parameter.

Extra Practice!

If you get through the exercises above, congratulations!

For extra practice, try some Practice-It exercises.

Task 4: Submit your work

You should show the paper with your work on Task 2 to the teaching assistant.

You should use Apollo to submit the following files:

Don’t worry if you didn’t finish all of the tasks. You should just submit whatever work you were able to complete during lab.

Warnings

  • Make sure to use these exact file names, or Apollo will not accept your files. If Apollo reports that a file does not have the correct name, you should rename the file using the name listed in the assignment or on the Apollo upload page.

  • Make sure that you do not try to submit a .class file or a file with a ~ character at the end of its name.

  • Before submitting your files, make sure that your BU username is visible at the top of the Apollo page. If you don’t see your username, click the Log out button and login again.

  • If you make any last-minute changes to one of your Java files (e.g., adding additional comments), you should compile and run the file in DrJava after you make the changes to ensure that it still runs correctly. Even seemingly minor changes can cause your code to become unrunnable.

  • If you encounter problems with Apollo, close your browser and try again. If possible, you may also want to wait an hour or two before retrying. If you are unable to submit and it is close to the deadline, email your homework before the deadline to cs112-staff@cs.bu.edu

Here are the steps:

  1. Login to Apollo, using the link in the left-hand navigation bar. You will need to use your Kerberos user name and password.
  2. Check to see that your BU username is at the top of the Apollo page. If it isn’t, click the Log out button and login again.
  3. Find the appropriate lab section on the main page and click Upload files.
  4. For each file that you want to submit, find the matching upload section for the file. Make sure that you use the right section for each file. You may upload any number of files at a time.
  5. Click the Upload button at the bottom of the page.
  6. Review the upload results. If Apollo reports any issues, return to the upload page by clicking the link at the top of the results page, and try the upload again, per Apollo’s advice.
  7. Once all of your files have been successfully uploaded, return to the upload page by clicking the link at the top of the results page. The upload page will show you when you uploaded each file, and it will give you a way to view or download the uploaded file. Click on the link for each file so that you can ensure that you submitted the correct file.