Two declared constructors in the inner class

I have an open class with a private class inside it:

public class A {

   private class B
   {
   }

   private final B b = new B();

   public static void main(String[] args) {
       Class<?> bClass = A.class.getDeclaredClasses()[0];
       Constructor<?>[] declaredConstructors = bClass.getDeclaredConstructors();
       System.out.println(declaredConstructors.length);  //result = 2
   }
}

The problem is that the declared constructors in class B are equal to two.

Although in other cases the number of constructors in class B is equal to one:

public class A {

   private class B
   {
       public B()
       {
       }
   }

   private final B b = new B();

   public static void main(String[] args) {
       Class<?> bClass = A.class.getDeclaredClasses()[0];
       Constructor<?>[] declaredConstructors = bClass.getDeclaredConstructors();
       System.out.println(declaredConstructors.length);  //result = 1
   }
}

and

public class A {

   private class B
   {
   }

   public static void main(String[] args) {
       Class<?> bClass = A.class.getDeclaredClasses()[0];
       Constructor<?>[] declaredConstructors = bClass.getDeclaredConstructors();
       System.out.println(declaredConstructors.length);  //result = 1
   }
}

The question is, why are there 2 constructors in the first case? Thank!

+4
source share
1 answer

As mentioned in chrylis, you see a synthetic constructor here.

Basically, whenever you get access to the private attributes of a nested class from a nesting class, the compiler needs to create synthetic methodaccess for this.

, , , ( , "2" ).

.

, , .

, 13.1.7 Java (https://docs.oracle.com/javase/specs/jls/se7/html/jls-13.html), .

, , , ( ): ?

, , : https://www.javaworld.com/article/2073578/java-s-synthetic-methods.html ( , , )

+5

Source: https://habr.com/ru/post/1694452/


All Articles