09 - Inner Classes - Exercise
Overview
We will work with the Employee project, replacing the external comparator classes with inner classes.
Task - Provide the Comparator as inner class
In the project you created earlier locate your Employee class. Inside this class definition, provide a new class
EmployeeNameComparator
, which implementsjava.util.Comparator
. Make the classpublic
andstatic
(thus it is what is called a 'Nested Inner Class').Provide the
compare
method - copy and paste your earlier implementation.Note that, since the class is defined within the
Employee
class, you do in fact have access to theprivate
variable directly, i.e. you do not even need to use yourgetName()
method. That's part of the purpose of Inner Classes in Java.In your main program, change the implementation so that the sort method uses your new nested class.
Print out the contents of the List once more, and test to see if your sorting has worked. Run and test your application.
In your
main()
method, provide another sort, this time via theEmployee
's age. Use an anonymous class to do this:Collections.sort(yourList, new Comparator<Employee>() { public int compare(Employee e1, Employee e2) { //your code here } });
If two
Employee
's have the same age (quite likely), then use a secondary sort criterion of their name. What is the best way to achieve this?The benefit of anonymous classes is that you can use local variables from the outer method inside their code, and that the coupling is low (i.e. only the line of code which contains the class can use it, so any changes can be made in the assurance that there are no repercussions anywhere else).
Run your code and check the results.