Inner Class in Java, when to use?

Asked

Viewed 4,523 times

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 to use Inner class? I have not yet come across a situation where there was no alternative.

2 answers

8


Usually the purpose of a Inner class is to separate functionalities to make code more organized, or when specific functionality requires a separate class, but is too specific to create a separate class.

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

An example of this case can be seen in the 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> {
    //...
}

3

There is always an alternative to the inner class.

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

The official documentation extract :

Use a non-static nested class (or Inner class) if you require access to an enclosing instance’s non-public Fields and methods. Use the Static nested class if you don’t require this access.

Obviously, we don’t create an inner class, if you know, it may be necessary elsewhere.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.