C211 Problem Solving and Programming II

C211 I211 Lab 7

Due Date: Monday, October 9, 2023.

Ex. 1. Abstract Classes and Interfaces

In this lab, we will implement a project that uses an abstract class and an interface in Java.

a. Abstract Class

Create a project called lab6 and a package inside it called lab7. Add an abstract class called Pet to the package, not containing the main method. The class should contain:

Add a second class to the project called TestPets containing the main method. Try declaring a variable of type Pet and assigning it a new object of this type to see what kind of error you get.

b. Derived Classes.   Add three more classes to the project, called Cat, Dog, and Parrot. Implement the three abstract methods in each of these classes, without the abstract keyword. Add a constructor with a name and a year to each of these classes.

In the class TestPets, in the main, declare an array of the type Pet and assign it an array with 6 element. Then assign two objects of each of the derived classes to the elements of the array using the constructors with a name and a birth year.

Use a for loop to output each of the objects of the array. Then use another for loop to call the methods makeSound and playTrick on each object.

c. Sorting.   Now we would like to sort the array of pets. We need to add implements Comparable<Pet> to the class Pet. Then in the class, define the function

@Override
public int compareTo(Pet p)

In this function, return the value of the year of the target object (this) minus the year of the object p.

In the main, add a call to Arrays.sort() with the array of pets as parameter, then output the array again. You will need to import java.util.Arrays for this.

Test the program to make sure that all the functionality works.

 

Lab Submission

Homework 7 will cover a different topic and will be due in two weeks. We will have a separate assignment on Canvas for it. All .java files created for this project should be uploaded to Canvas in Assignments - Lab 7. This week, there is also the Project Phase 1 to complete.