What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?
public Module() { this.name = ""; this.credits = 0; this.hours = 0; } public Module(String name, int credits, int hours) { this.name = name; this.credits = credits; this.hours = hours; }
Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors. This is called the default constructor.
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .
In such case, Java compiler provides a default constructor by default. There are two types of constructors in Java: no-arg constructor, and parameterized constructor. Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class.
The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass.
Neither of them. If you define it, it's not the default.
The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are String
, int
and int
, and that the class itself is public:
public Module() { super(); this.name = null; this.credits = 0; this.hours = 0; }
This is exactly the same as
public Module() {}
And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.
Reference: Java Language Specification
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because
A default constructor is created if you don't define any constructors in your class. It simply is a no argument constructor which does nothing. Edit: Except call super()
public Module(){ }
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