/
09 - Inner Classes - Exercise

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

  1. In the project you created earlier locate your Employee class. Inside this class definition, provide a new class EmployeeNameComparator, which implements java.util.Comparator. Make the class public and static (thus it is what is called a 'Nested Inner Class').

  2. Provide the compare method - copy and paste your earlier implementation.

  3. Note that, since the class is defined within the Employee class, you do in fact have access to the private variable directly, i.e. you do not even need to use your getName() method. That's part of the purpose of Inner Classes in Java.

  4. In your main program, change the implementation so that the sort method uses your new nested class.

  5. Print out the contents of the List once more, and test to see if your sorting has worked. Run and test your application.

  6. In your main() method, provide another sort, this time via the Employee'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    } });
  7. 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?

  8. 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).

  9. Run your code and check the results.