Inner Class in Java, when to use?

11

Sometimes I find class codes with inner class , such as:

class ClasseExterna {

    private int a = 10;
    // ...

    class InnerClass {  

        public void accessOuter() {
            System.out.println("Outra classe  " + a);
        }

        // ...
    }
}

I always wonder:

Why and when should I use inner class ? I have not yet come across a situation where there was no other alternative.

    
asked by anonymous 22.04.2015 / 21:02

2 answers

8

Normally the purpose of an Inner class is to separate the functionality to make the code more organized, or when the specific functionality needs a separate class, but it is very specific to create a separate class .

An example I can cite is a class that implements Iterable and is declared Iterator as an Inner class .

An example of this case can be seen in class java.util.ArrayList (I removed the implementation to not get too long):

public Iterator<E> iterator() {
    return new Itr();
}

private class Itr implements Iterator<E> {
    //...
}
    
23.04.2015 / 00:47
3

There is always an alternative to the inner class.

In general, we use an inner class when you need to access non-public attributes / methods.

The official documentation extract:

  

Use the non-static nested class (or inner class) if you require access   to an enclosing instance's non-public fields and methods. Use static   nested class if you do not require this access.

Obviously, we do not create an inner class, if you know, it may be needed elsewhere.

    
22.04.2015 / 21:24