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() {}
}
By default, constructors are defined in public section of class.
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.
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.
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.
It depends on your class visibility.The compiler uses the class visibility and generates a no-arg default constructor with the same visibility
As said in JLS
If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:
As classes visibility is public, it will always be a public constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With