Will the compiler-generated default constructor be public?
Asked Answered
A

7

8

When I write a class Widget.java

public class Widget {
    int data;
    String name;
}

will the compiler-generated constructor be public or default?

public would be like

public class Widget {
    int data;
    String name;
    public Widget() {}
}

whereas default similar to

public class Widget {
    int data;
    String name;
    Widget() {}
}
Angiosperm answered 13/2, 2014 at 9:50 Comment(0)
P
10

It depends on your class visibility.The compiler uses the class visibility and generates a no-arg default constructor with the same visibility

Propst answered 13/2, 2014 at 9:52 Comment(0)
I
6

As said in JLS

If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:

  1. If the class is declared public, then the default constructor is implicitly given the access modifier public;
  2. If the class is declared protected, then the default constructor is implicitly given the access modifier protected;
  3. If the class is declared private, then the default constructor is implicitly given the access modifier private;
  4. Otherwise, the default constructor has the default access implied by no access modifier
Insert answered 13/2, 2014 at 9:53 Comment(0)
M
1

As classes visibility is public, it will always be a public constructor.

Manama answered 13/2, 2014 at 9:53 Comment(0)
C
1

It will be public as the class visibility is public

public Widget() {}
Cornstarch answered 13/2, 2014 at 9:53 Comment(0)
A
1

It will be public Widget() {}

Anthropolatry answered 13/2, 2014 at 9:55 Comment(0)
S
1

Depends on class visibility. For your class dafault constructor is going to be public.

In a class type, if the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier.

From here.

Shippen answered 13/2, 2014 at 9:57 Comment(0)
A
0

If your class is public then the default constructor would be public so in your case, Since the Widget class is public its default constructor supplied by the compiler would also be public. See this

Adkins answered 13/2, 2014 at 9:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.