Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the compiler-generated default constructor be public?

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() {}
}
like image 287
towi Avatar asked Feb 13 '14 09:02

towi


People also ask

Is a default constructor always public?

By default, constructors are defined in public section of class.

Will compiler create a default constructor?

In C++, the compiler creates a default constructor if we don't define our own constructor. In C++, compiler created default constructor has an empty body, i.e., it doesn't assign default values to data members.

What does a default constructor generated by the compiler perform?

In both Java and C#, a "default constructor" refers to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class. The default constructor implicitly calls the superclass's nullary constructor, then executes an empty body.

Does the compiler always provide a default copy constructor?

In C++, the compiler automatically generates the default constructor, copy constructor, copy-assignment operator, and destructor for a type if it does not declare its own. These functions are known as the special member functions, and they are what make simple user-defined types in C++ behave like structures do in C.


3 Answers

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

like image 154
Kumar Abhinav Avatar answered Sep 30 '22 18:09

Kumar Abhinav


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
like image 44
Abimaran Kugathasan Avatar answered Sep 30 '22 19:09

Abimaran Kugathasan


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

like image 29
Dark Knight Avatar answered Sep 30 '22 19:09

Dark Knight