Java Reference
In-Depth Information
return 0;
}
return this.name.compareTo(person.name);
}
@Override
public String toString() {
return name;
}
protected String name;
}
This is a simple class representing a person. It implements the
Comparable<Person>
interface so you
can use a
BinaryTree<Person>
object to store and sort objects of type
Person
. This works just as well as
the
BinaryTree<String>
and
BinaryTree<Integer>
examples.
However, you might possibly subclass the
Person
type like this:
public class Manager extends Person {
public Manager(String name, int level) {
super(name);
this.level = level;
}
@Override
public String toString() {
return "Manager " + super.toString() + " level: " + level;
}
protected int level;
}
This class defines a special kind of
Person
— a manager no less! You have just one extra field specifying
the level that reflects where the manager sits in the corporate pecking order. You also have a version of
the
toString()
method that presents the
Person
as a manager with his or her level. The class inherits the
implementation of the
Comparable<Person>
interface from the base class. If that's sufficient for differen-
tiating two persons, it should be okay for separating two managers. However, it's not good enough for the
BinaryTree<T>
type. You could try adding
Manager
objects to a binary tree like this:
BinaryTree<Manager> people = new BinaryTree<>();
Manager[] managers = { new Manager("Jane",1), new Manager("Joe",3), new
Manager("Freda",3)};
for(Manager manager: managers){
people.add(manager);
}
However, it doesn't work. If you insert this fragment at the end of
main()
in the previous example, you
get a compiler error message relating to the statement that creates the
BinaryTree<Manager>
object; it says
something along the lines of “type parameter Manager is not within its bound."
The problem is that your
BinaryTree<T>
class requires that the
Manager
class should implement the
Comparable<Manager>
interface. The inherited implementation of
Comparable<Person>
is not acceptable.