Java Reference
In-Depth Information
}
}
Directory "TryParameterizedMethods"
The output should be as follows:
Ann
Manager Freda level: 3
Manager Jane level: 1
Manager Joe level: 3
Mary
Stan
Tina
Will
How It Works
You create an object of a BinaryTree type that stores Person objects:
BinaryTree<Person> people = new BinaryTree<>();
You then define an array of Manager objects and add those to the people binary tree:
Manager[] managers = { new Manager("Jane",1), new
Manager("Joe",3),
new
Manager("Freda",3)};
for(Manager manager : managers){
people.add(manager);
}
The add() method is defined as a parameterized method in the BinaryTree<> type definition, where
the method's parameter, E , has an upper bound that is the type variable for the BinaryTree<> type. This
enables the add() method to accept arguments that are of a type that can be type Person or any subclass
of Person . You defined the Manager class with Person as the base class so the add() method happily
accepts arguments of type Manager .
Just to demonstrate that you can, you create an array of Person objects and add those to the people bin-
ary tree:
Person[] persons = {
new Person("Will"), new Person("Ann"), new
Person("Mary"),
new Person("Tina"), new Person("Stan")};
for(Person person : persons) {
people.add(person);
}
You now have a mix of Person and Manager objects in the binary tree. You list the contents of the binary
tree in ascending alphabetical order by calling the parameterized listAll() method that you defined as
a static member of the TryParameterizedMethods class:
Search WWH ::




Custom Search