Java Reference
In-Depth Information
9. What are the differences between an abstract class and an interface?
8.18 Lab
Create a program that keeps track of students and their advisors. Your program will
have a
Test
class, a
Student
class, an
Advisor
class, and a
Person
class. The
Student
and
Advisor
classes should inherit from the abstract
Person
class. The
Person
class should
implement the interface
Comparable
in order to allow the use of
Collections.sort
to sort
its elements. Remember that an interface is similar to a class, but it contains only method
definitions and no method bodies. A class
implements
rather than
extends
an interface.
Implementing an interface means that the subclass will implement all the methods in the
interface. The interface
Comparable
contains the single
compareTo
method. The objects of
every class that implements the interface
Comparable
can be sorted because the
compareTo
method can be called on them. People should be compared based on their names. Here are
the variables and methods of each class.
public abstract class
Person
implements
Comparable
<
Person
>
:
private
String name
public
Person(String name)
public
String toString()
public int
compareTo(Person other )
public
String getName ()
public class
Advisor
extends
Person :
private
ArrayList
<
Student
>
students
public
Advisor(String name)
public
String listStudents()
//returns the advisor ' s
// students sorted by name
public void
addStudent(Student s)
public
String toString()
public class
Student
extends
Person
private
Advisor advisor
public
Student(String name, Advisor advisor )
public
String listAdvisor()
//returns the student ' s advisor
Note that the constructor of the
Student
class needs to add the new student to the list
of students for the specified advisor. Create an
ArrayList<Person>
in the main method
of the
Test
class to store the current list of people. You can populate the
ArrayList
with
example values (i.e., you do not have to read them from the keyboard). When students
are printed, their name and the name of their advisor should appear. When advisors are
printed, their name and the names of their students (in sorted order) should appear. Sort
the elements in the
ArrayList
of people and print them.