Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of an inner class

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.

like image 225
Krishna Chaitanya Avatar asked Nov 26 '13 03:11

Krishna Chaitanya


People also ask

What are the advantages of inner class?

Inner classes are used to develop a more readable and maintainable code because they logically group classes and interfaces in one place. Easy access, as the inner object, is implicitly available inside an outer Code optimization requires less code to write. It can avoid having a separate class.

Why do we use inner class in Python?

We do not need to search for classes in the whole code, they all are almost together. Though inner or nested classes are not used widely in Python it will be a better feature to implement code because it is straightforward to organize when we use inner class or nested class.

What is meant by inner class in Java?

Java Inner Classes In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is to group classes that belong together, which makes your code more readable and maintainable.

What is the main use of inner classes quizlet?

We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable. Additionally, it can access all the members of outer class including private data members and methods.


2 Answers

You should inner classes if you need something specific to the class your working with. A good example of an inner class can be found here: java.awt.geom.Ellipse2D and the corresponding Ellipse2D.Double and Ellipse2D.Float (Ellipse2D source code). You could place those classes in a package, but they make a lot more sense as nested classes. They directly correspond to Ellipse2D and will have no use elsewhere; also, the fact that they are nested improves readability in code that uses them. On another note, if an inner class is very likely to be useful when more general, it is often better to generalize it and make a regular class.

Also, inner classes can directly access variables in the outer class. That means that an inner class can be used to change the outer class. It is still possible to get an instance of it to be used outside of either class. To illustrate what I am saying:

public class Example {
    public static void main(String[] args) {
        Foo foo = new Foo();
        Foo.Bar bar = foo.getBar(); //note, cannot call new Foo.Bar(); as Bar is dependent on Foo
        for (int i = 0; i < 50; i++){
            System.out.println(bar.get());
        }
    }
}
class Foo {
    int val;
    Bar b;

    public Foo(){
        b = new Bar();
    }
    public Bar getBar(){
        return b;
    }
    public class Bar{
        public Bar(){
            val++;
        }
        public int get(){
            return val++;
        }
    }
}

Another possible use of inner classes is to create something like a wrapper class for an the truly wanted inner class, especially useful for a recursive class. This is used for implementing a LinkedList. At one time, I implemented such a list, not realizing that anything of the sort had been made before. The idea is that you have your LinkedList class, and a Node class within it (where each node only points to the next/previous node and holds a single value). Doing it this way simplifies the code. However, it doesn't make any sense for the Node class to be external to LinkedList, because what type of "node" would it be? Thus it should be an internal class.

like image 187
Justin Avatar answered Oct 23 '22 09:10

Justin


Some classes don't make make much sense on their own - they only make sense in the context of another class. Inner classes are helpful at defining this kind of relationship - they allow the developer to express the relation between highly cohesive classes more explicitly.

see more

As an example consider a Node in a Graph. A Node has a list of peer Nodes which it can reach itself. It makes sense to define a Peer class as an inner class of Node. For example:

public class Node
{
private String name;
private List peers = new ArrayList();

private Node( String name )
{
this.name = name;
}

/**
* Represents a peer node that is reachable from this node
*/
class Peer
{
private Node node;
private int distance;
}
}
like image 1
Rakesh KR Avatar answered Oct 23 '22 09:10

Rakesh KR