Is InnerClass object created at what time?

3

I have a class which contains an InnerClass, I would like to know if the moment I give new ClassePrincipal() the InnerClass is also created?

    
asked by anonymous 03.03.2015 / 19:26

2 answers

3

An InnerClass is created when using the new operator 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";
        }
    }
}

Output:

  

Command: new outter
  Outter created
  Command: new inner
  Inner maid
  Command: inner toString
  inner toString
  Command: static inner toString
  static inner toString

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

    
03.03.2015 / 19:41
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
    
03.03.2015 / 19:35