Old version
This is the CS 112 site as it appeared on May 8, 2019.
Lab 4: Inheritance and Polymorphism
Task 1: Understand and use inheritance
As we discussed 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 Eclipes along with a simple
progam testDriver.java that we can
use to test the methods of our classes.
Review each file 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!
-
Which class is the superclass? Which is the subclass? What does it mean that the
Catclass extends theAnimalclass? -
The
Catclass cannot directly access the fields it inherits fromAnimal. Why not? -
The subclass constructor typically calls the superclass constructor to initialize the inherited fields. Write a constructor for the
Catclass 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.Update the test program to create an instance of class
Cat.Cat c = new Cat("Kitty", false); -
To manipulate the inherited fields, the subclass can use the inherited accessor and mutator methods. Write a
toStringmethod for theCatclass above. It should return a string consisting of the cat’s name followed by either" (short-haired)"or" (long-haired)".Update the test program to test your method.
System.out.println( c );
-
The subclass can override an inherited method, replacing it with a version that is more appropriate. Write an
isSleepingmethod for theCatclass. It should reflect the fact that cats seem to sleep all of the time!Update the test program to test your method.
-
Let’s say that we now want to define a class called
Abyssinianfor cats that belong to that particular breed of short-haired cat. Which class should it extend? -
Go ahead and create a class named
Abyssinian, 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.
Once your class is created, go ahead and test out the methods in your main program.
-
-
Another possible class for this hierarchy of animals is the
Dogclass, which you should examine now, although you don’t need to open it in Eclipse. In addition to its inherited fields and methods, it has abooleanfieldisSmall, and methodsisSmall()andbark(). -
Let’s say that we have created an
Abyssinianobject and assigned it to the variablea:Abyssinian a = new Abyssinian("Abby");For each of the following method calls:
-
Indicate whether it will compile. Because the variable
ais declared to be of typeAbyssinian, a method call usingawill compile if there is a corresponding method insideAbyssinianobjects – either defined in theAbyssinianclass 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 to test:
-
a.getNumLegs() -
a.isExtroverted() -
a.isSleeping(12, 30) -
a.isSmall() -
a.toString() -
a.equals(a)
-
-
You will notice a static method defined in the
Animalclass namedprintAnimalName. How can you call this method in your main program to print out the names of all the animal objects you have created? Note that it is astaticmethod. How does this differ from the other methods of the class?Update the test program to test this method.
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 {
...
}
-
Draw an inheritance hierarchy for these classes.
-
Which of these assignments would be allowed, taking into account the rules of polymorphism?
-
B myObj = new A(); -
B myObj = new C(); -
C myObj = new A(); -
A myObj = new B(); -
D myObj = new B();
-
Task 3: Memory diagrams and the ArrayBag class (optional)
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!
-
What are the fields of the
ArrayBagclass, and why did we include them in our definition? -
Note that there isn’t a
getItem()method for accessing a specific item in the bag. Instead, there is a method calledgrab()which accesses a random item in the bag. Why does this make sense, given the characteristics of a bag? -
In lecture, we looked at the
add()method, which adds a single item to theArrayBag. Let’s draw a memory diagram (stack and heap) of anArrayBagobject calledbas theadd()method is called on it for the first time. Show the addition of the string"don't blink" -
Open
ArrayBag.javain Eclipse and compile the class. -
Write a simple main() test program to test the following:
-
complete the following statement to create an
ArrayBagobject with the default maximum size:> ArrayBag b = ...
-
add
"don't blink"to thatArrayBag - add
"baggy"to thatArrayBag
-
-
After performing these operations, output what your
ArrayBaglooks like:> System.out.println(b) {don't blink, baggy}Note that the
toString()method of theArrayBagclass is being invoked, and that method produces the string that is displayed whenbis evaluated. -
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?
-
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
Stringobject, an exception would be thrown. -
Add a non-static method called
hasMoreRoom()that takes as a parameter anotherArrayBagcalledother, and that returnstrueif the calledArrayBaghas more room left for items (i.e., more unused array elements) thanotherdoes, andfalseotherwise.If
otherisnull, the method should throw anIllegalArgumentException.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) falseHint: Because this method is part of the
ArrayBagclass, it can directly access the private fields of theArrayBagthat is passed in as a parameter.
Extra Practice!
If you get through the exercises above, congratulations!
For extra practice, try some Practice-It exercises.
-
Go to Practice-It.
-
Create an account if needed.
-
Select the group of problems entitled Building Java Programs, 3rd edition.
-
Try problems from either of these groups of problems:
- BJP3 Chapter 9: Inheritance
- BJP3 Chapter 12: Recursion (which is not in this lab, but is being covered in lecture and on PS 3!)
The system will test your solution and tell you whether it is correct.