I am reading about inner classes in an interface and class. I could not understand about the real use. However I dont want to discuss anything about inner classes inside an interface in this post.
I have used inner classes as a callback till now. I can do the same declaring the class outside somewhere.
Suppose that I have a list of students and I want to sort them by id. I have to implement Comparator interface and provide it as an argument to Collections's sort method.
public class StudentList {
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
Student student = new Student();
student.setId(1);
student.setName("Krishna");
students.add(student);
student = new Student();
student.setId(2);
student.setName("Chaitanya");
students.add(student);
Collections.sort(students, new StudentList().new MyComparator());
}
public class MyComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
if (o1.getId() < o2.getId()) {
return 1;
} else if (o1.getId() > o2.getId()) {
return -1;
} else {
return 0;
}
}
}
}
I can do the same like this also
public class StudentList {
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
Student student = new Student();
student.setId(1);
student.setName("Krishna");
students.add(student);
student = new Student();
student.setId(2);
student.setName("Chaitanya");
students.add(student);
Collections.sort(students, new MyComparator());
}
}
class MyComparator implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
if (o1.getId() < o2.getId()) {
return 1;
} else if (o1.getId() > o2.getId()) {
return -1;
} else {
return 0;
}
}
}
I dont think inner class in the above example adds any significant importance unless it is declared as a private class. When I declare it as private, only the enclosing class can use it. It means the class is strongly binded with the enclosing class and I see some advantage of having so.
Can anyone please explain me the true importance/significance of using/writing inner classes in an application.