1

D.java

   package com.model; 
   public class D {
     public int z;
    }

B.java

package com;
import com.model.D;

class A {
 public int x;
}

class C {
 public int y;
 public C() {}
}
        
public class B {
    public static void main(String args[] ) throws Exception {
        
        Class clssA = A.class;
        Constructor[] constructorA = clssA.getConstructors();   // []
        
        Class clssC = C.class;
        Constructor[] constructorB = clssC.getConstructors();  // [public com.C()]

        Class clssD = D.class;
        Constructor[] constructorD = clssD.getConstructors();  // [public com.model.D()]
        }
}

As per my understanding, the Java compiler provides a default (public no-arg) constructor for classes without any constructor, then why the output of getConstrucors() call for class A and class C are different?

Also, class A and class D have the same class structure with the only difference of package name but the getConstructors() for class D returns a non-empty array?

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
dope
  • 303
  • 4
  • 14
  • @HenryTwist I don't see anything in your duplicate that answers this question. – user207421 Apr 22 '21 at 01:13
  • 4
    Your understanding is incorrect. Java generates a default constructor with the same access modifier as the class. [JLS #8.8.9](https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-8.8.9). As `A` isn't public, the generated constructor isn't either: and `getConstructors()` only returns public constructors. – user207421 Apr 22 '21 at 01:16
  • 1
    @user207421 Oh really? The accepted answer says only public constructors are returned and if the "class is NOT public -- its default constructor won't be either". I guess I thought that was the same as your comment (although definitely less explicit). – Henry Twist Apr 22 '21 at 02:15

0 Answers0