java – Why can an inner class be static and an outer class not?

Question:

It is possible to have a static inner class:

public class ClasseExterna{
    public static class ClasseInterna(){
    }
}

And it's not possible to have a static external class:

public static class ClasseExterna{
    public static class ClasseExterna(){
    }
}

What is the difference between one situation and another?

Answer:

static means that something belongs directly to the class and does not need an instance of that class in order to access it.

What can be static:

  • Methods;
  • Attributes; and
  • Nested classes.

Static Nested Class x Non-Static Nested Class

Comparing two classes, one static and one not, but both nested, we will see what the definition of static means, which I quoted above:

class Externa {
    static class Estatica {
        void imprime() {
            System.out.println("método da classe aninhada estática");
        }
    }
    class NaoEstatica {
        void imprime() {
            System.out.println("método da classe aninhada NÃO estática");
        }   
    }
}

class TesteNestedClasses {
    public static void main(String[] args) {
        /*
         * repare que para criar uma instancia da classe estatica não foi necessário
         * criar uma instância da classe Externa
         */
        Externa.Estatica estatica = new Externa.Estatica();
        estatica.imprime();

        /*
         * não é possível criar uma classe não estática sem uma instancia da classe Externa
         */
        //Externa.NaoEstatica naoEstatica = new Externa.NaoEstatica(); //ERRADO!!!
        Externa externa = new Externa();
        Externa.NaoEstatica naoEstatica = externa.new NaoEstatica(); 
        naoEstatica.imprime();
    }
}

Result:

static nested class method
nested class method NOT static

We cannot have an outer (ie, non-nested) class of static type because as defined by the definition, static is what can be accessed directly by the class, without the need for an instance, so if the class is not nested to whom it is would it belong if it were static? Something like that doesn't make sense, so there's no way to implement something like that.

Scroll to Top