Innerclass object is created at what point?

Asked

Viewed 60 times

3

I have a class which contains an Innerclass, I wonder if at the moment I give new ClassePrincipal() Innerclass is also created?

2 answers

3

An Innerclass is created when using the operator new to create an instance of it. For example:

public class Principal {
    public static void main(String[] args) {
        System.out.println("Comando: new outter");
        Outter out = new Outter();

        System.out.println("Comando: new inner");
        Outter.Inner in = out.new Inner();

        System.out.println("Comando: inner toString");
        System.out.println(in);     

        System.out.println("Comando: static inner toString");
        System.out.println(new Outter.StaticInner());
    }
}

class Outter {
    public Outter() {
        super();
        System.out.println("Outter criada");
    }
    public class Inner {
        public Inner() {
            super();
            System.out.println("Inner criada");
        }
        @Override
        public String toString() {
            return "inner toString";
        }
    }
    public static class StaticInner {
        @Override
        public String toString() {
            return "static inner toString";
        }
    }
}

Exit:

Control: new outter
Outter created
Control: new Inner
Inner maid
Remote control: Inner toString
Inner toString
Remote control: Static Inner toString
Static Inner toString

Note the above code that the constructor of the internal classes was only called when explicitly created with a new, for both static and non-static inner class. Before that there was no reason why the inner classes had been instantiated.

1

No. The Inner class is only created when you make a static reference to it or instantiate it.

See the example below:

public class Classe {

    static {
        System.out.println("Carregou Classe");
    }

    public Classe() {
        System.out.println("Instanciou Classe");
    }

    public static void main(String[] args) {
        new Classe();
    }

    static class InnerClasse {

        static {
            System.out.println("Carregou InnerClasse"); // não será chamado
        }

        public InnerClasse() {
            System.out.println("Instanciou InnerClasse"); // não será chamado
        }
    }
}

The output of this program is:

Carregou Classe
Instanciou Classe
  • In his example his InnerClasse is not within any other class, you have not confused something when creating your example?

  • @Math, thank you, had me confused. I already edited the answer.

  • It turned out that my answer was very similar to yours, I was not understanding well until I stopped and read carefully. Well, here goes my +1

Browser other questions tagged

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