189

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;
}
shekhar
  • 1,372
  • 2
  • 16
  • 23
antanis
  • 1,909
  • 2
  • 12
  • 4

13 Answers13

302

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.

Clarification

Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because

  • the question got the defaults wrong, and
  • the constructor has exactly the same effect whether they are included or not.
OrangeDog
  • 36,653
  • 12
  • 122
  • 207
  • 27
    Your statement **It initialises any uninitialised fields to their default values** sounds a bit ambiguous. Even if we put explicit constructors(with args) or even provide a no arg constructor instance variables are always initialized with default values. I don't think it has anything to do with default constructor. – Aniket Thakur Sep 12 '13 at 14:01
  • Everything that the default constructor does will be done for constructors that don't do those things themselves. – OrangeDog Sep 12 '13 at 14:31
  • 2
    @OrangeDog Where do you see in the specification the statement that the user defined nullary constructor without parameters is not called the default constructor? – Łukasz Rzeszotarski Sep 13 '13 at 05:32
  • 1
    @ŁukaszRzeszotarski where do you see anything that suggests otherwise? Occam's razor. – OrangeDog Sep 13 '13 at 08:57
  • 1
    @OrangeDog In the specification states 'If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided', but it doesn't mean that mentioned constructor provided by developer is not a default one (I know this is language's purism). On the other hand in wikipedia(I know wiki is not a language specification), though there states 'A user defined constructor that takes no parameters is called a default constructor too.[4][5]' – Łukasz Rzeszotarski Sep 13 '13 at 11:42
  • You should read and provide Wikipedia's sources, not Wikipedia itself. – OrangeDog Sep 13 '13 at 13:04
  • 2
    I actually just had the question "does the default constructor initialize the instance members of the class" in the OCA certification exam, and the answer was no. – eis Dec 02 '13 at 20:07
  • 13
    @AniketThakur +1 it is not just ambiguous, it is false; The default constructor does not initialise anything. As the reference given here says: "the default constructor simply invokes the superclass constructor with no arguments". Uninitialised fields are initialised by other mechanisms also described in this reference. +1 to OrangeDog for providing a good reference. – Superole Jan 28 '14 at 08:38
  • What's actually ambiguous is the exact statement in the spec: "If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared." This is an "if" and not "iff", so it's unclear whether the converse "If a default constructor with no formal parameters and no throws clause is implicitly declared, then a class contains no constructor declarations" is true. – Su Zhang Apr 04 '14 at 23:53
  • maybe we can call this default(***synthesized***) default-constructor. For me, default constructor is just a constructor ***callable*** with no argument. – Gab是好人 Apr 13 '17 at 14:48
  • @Gab是好人 what it is for you does not make it true. – OrangeDog Apr 13 '17 at 14:50
  • @OrangeDog then how do you call a user-defined no-argument constructor? – Gab是好人 Apr 13 '17 at 14:52
  • 2
    @Gab是好人 it's called a "no-argument" or "no-arg" constructor. – OrangeDog Apr 13 '17 at 15:00
  • @OrangeDog OK, I agree. I used the C++ way to call the Java default constructor. – Gab是好人 Apr 14 '17 at 12:14
  • 1
    Also have to be careful because the generated default no-arg constructor invokes super class' default no-arg constructor. If the superclass does not have one (because the super class author rolled her own non no-arg constructors), then you'll get a compile time error. See https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html, search for "In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does" – Jose Quijada Jul 14 '20 at 16:39
  • From [jls-12.5](https://docs.oracle.com/javase/specs/jls/se16/html/jls-12.html#jls-12.5), all the instance variables "are initialized to their default values" right after the memory allocation for the object, and _before_ the processing of indicated constructor. So the default constructor has nothing to do with the initialization of instance variables. – muzimuzhi Z Aug 18 '21 at 05:12
  • @muzimuzhiZ did you finish reading the answer? – OrangeDog Aug 18 '21 at 09:13
  • @OrangeDog my bad – muzimuzhi Z Aug 18 '21 at 14:03
  • I came here asking "why create a no-arg constructor" and you answered it: "However, if you define at least one constructor, the default constructor is not generated." – caduceus Jan 07 '23 at 21:21
41

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(){
}
Jim
  • 22,354
  • 6
  • 52
  • 80
  • 4
    To make it explicite: if you write your own constructor, java will not create the default constructur. So if you need a constructor with arguments and a constructor without arguments (like the default constructor), the you have to write both! – Ralph Dec 20 '10 at 10:30
  • 2
    It should also be noted that if the superclass *doesn't* have a no-argument constructor, the subclass cannot have a default constructor (because Java doesn't know how to use the constructors that are there by default). – Donal Fellows Dec 20 '10 at 10:30
  • 8
    @Sergey This seems to disagree http://download.oracle.com/javase/tutorial/java/javaOO/constructors.html as does wikipedia. – Jim Dec 20 '10 at 10:32
  • 5
    [as does the Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.8.9)! I didn't realize there was such a difference between Java and C++ in terminology. – Sergei Tachenov Dec 20 '10 at 10:36
23

A default constructor is automatically generated by the compiler if you do not explicitly define at least one constructor in your class. You've defined two, so your class does not have a default constructor.

Per The Java Language Specification Third Edition:

8.8.9 Default Constructor

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

kem
  • 1,127
  • 8
  • 14
18

Hi. As per my knowledge let me clear the concept of default constructor:

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. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.

I read this information from the Java Tutorials.

Don Cruickshank
  • 5,641
  • 6
  • 48
  • 48
Koushik85
  • 181
  • 1
  • 2
7

Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.

The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.

Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).

public class Cube1 {
    int length;
    int breadth;
    int height;
    public int getVolume() {
        return (length * breadth * height);
    }

    Cube1() {
        length = 10;
        breadth = 10;
        height = 10;
    }

    Cube1(int l, int b, int h) {
        length = l;
        breadth = b;
        height = h;
    }

    public static void main(String[] args) {
        Cube1 cubeObj1, cubeObj2;
        cubeObj1 = new Cube1();
        cubeObj2 = new Cube1(10, 20, 30);
        System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
        System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
    }
}
Jake1164
  • 12,291
  • 6
  • 47
  • 64
sunil
  • 71
  • 1
  • 1
  • 3
    You should never do it like this, instead in the "default" constructor write this `this(10,10,10);` that will call the second constructor within your first constructor, which will make your code a lot cleaner, easier to understand, and refactored. – julian Apr 20 '15 at 23:48
  • @Israelg99 What is the exact terminology when we use `this(10,10,10);` ? – sgiri Aug 31 '17 at 10:45
  • @Israelg99 never mind, it is called **explicit constructor invocation** ref: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html – sgiri Aug 31 '17 at 10:47
6

General terminology is that if you don't provide any constructor in your object a no argument constructor is automatically placed which is called default constructor.

If you do define a constructor same as the one which would be placed if you don't provide any it is generally termed as no arguments constructor.Just a convention though as some programmer prefer to call this explicitly defined no arguments constructor as default constructor. But if we go by naming if we are explicitly defining one than it does not make it default.

As per the docs

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

Example

public class Dog
{
}

will automatically be modified(by adding default constructor) as follows

public class Dog{
    public Dog() {

    }
} 

and when you create it's object

 Dog myDog = new Dog();

this default constructor is invoked.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
5

default constructor refers to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors.

If there's no constructor provided by programmer, the compiler implicitly declares a default constructor which calls super(), has no throws clause as well no formal parameters.

E.g.

class Klass {
      // Default Constructor gets generated
} 

new Klass();  // Correct
-------------------------------------

class KlassParameterized {

    KlassParameterized ( String str ) {   //// Parameterized Constructor
        // do Something
    }
} 

new KlassParameterized(); //// Wrong  - you need to explicitly provide no-arg constructor. The compiler now never declares default one.


--------------------------------

class KlassCorrected {

    KlassCorrected (){    // No-arg Constructor
       /// Safe to Invoke
    }
    KlassCorrected ( String str ) {   //// Parameterized Constructor
        // do Something
    }
} 

new KlassCorrected();    /// RIGHT  -- you can instantiate
Yergalem
  • 1,603
  • 18
  • 14
  • 1
    Actually, default constructor != no-args constructor. A no-args constructor is **any** constructor with no arguments. A default constructor is the specific no-args constructor that is generated if no constructors are declared in a class. – Stephen C May 19 '17 at 13:19
  • 1
    I didn't say default constructor == no-args constructor but said also called . Similarily, you don't see the converse that no-args constructor is default constructor. Your second statement is what I tried to put. – Yergalem May 19 '17 at 16:59
  • You said - "default constructor is also called no-arg constructor ...". That **means** default constructor == no-args constructor. If that is not what you meant to your answer to mean, then you should correct it. "Your second statement is what I tried to put." - Unfortunately, what you wrote and my second sentence do not mean the same thing. – Stephen C May 19 '17 at 21:48
  • Thanks for your comment. I don't mean that. Now edited. – Yergalem May 21 '17 at 01:53
  • Your updated version is still incorrect. The correct thing to say is that the declaration is ADDED automatically. (The word "invoke" is about when a constructor is used ... not when it is declared.) Furthermore, it is only added if no other constructors AT ALL are declared. (Not just constructors with parameters.) Again: I don't know if you really know these things or not. But what you are saying (i.e. the words that you are writing) are misleading. – Stephen C May 21 '17 at 02:13
  • Hope the code speaks. I wrote it the description so quickly. I didn't proofread. Anyway, you're right. Corrected. Basically, the compiler adds (generates) the declaration of default constructor which implicitly calls super(). If you paid attention below the first line, I tried to clarify it. Thanks, Stephen. – Yergalem May 22 '17 at 14:28
  • The first couple of lines are the most important. They are what most people read. If you mislead them there ..... that's what they will remember! – Stephen C May 22 '17 at 14:56
3

If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.

In your case, there is no default constructor as you are adding them programmatically. If there are no constructors added by you, then compiler generated default constructor will look like this.

public Module()
{
   super();
}

Note: In side default constructor, it will add super() call also, to call super class constructor.

Purpose of adding default constructor:

Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.

That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.

user1923551
  • 4,684
  • 35
  • 29
  • Constructor duty is to initialize memory space, in which the object is created. The object initialization is Java Virtual Machine responsibility. – MaxZoom Apr 17 '15 at 21:03
  • @StephenC not according to [this](http://www.javaworld.com/article/2076614/core-java/object-initialization-in-java.html) article – MaxZoom May 23 '17 at 17:05
  • @MaxZoom - You misunderstood the article I think. It says this: *"To guard against such a scenario, Java makes certain that memory is initialized, at least to predictable default values, before it is used by any code."* - That's the JVM does that. And the "any code" includes the code of the constructor. Besides, if you want a **reliable** source, read what the JLS specifies. – Stephen C May 23 '17 at 22:37
  • @StephenC That's right, JVM assigns default values. And as there is no much code in a default constructor, it is the only player in doing so. I understand the article correctly. As JLS does not provide much explanation about default constructor, I would appreciate some reliable source of information to support your point. – MaxZoom May 24 '17 at 02:27
  • But here's the problem. Your comment >>says<< constructor does memory initialization and JVM does object initialization. In fact, the JVM does the memory initialization (and creation of the heap node + object header) and the constructor(s) do the object initialization. – Stephen C May 24 '17 at 02:49
  • References to read: http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.5 and http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.new ... noting what it says about constructor invocation ... and http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.9 – Stephen C May 24 '17 at 02:51
2

When we do not explicitly define a constructor for a class, then java creates a default constructor for the class. It is essentially a non-parameterized constructor, i.e. it doesn't accept any arguments.

The default constructor's job is to call the super class constructor and initialize all instance variables. If the super class constructor is not present then it automatically initializes the instance variables to zero. So, that serves the purpose of using constructor, which is to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object.

Once we define our own constructor for the class, the default constructor is no longer used. So, neither of them is actually a default constructor.

uttsav
  • 169
  • 1
  • 4
0

When you don’t define any constructor in your class, compiler defines default one for you, however when you declare any constructor (in your example you have already defined a parameterized constructor), compiler doesn’t do it for you.

Since you have defined a constructor in class code, compiler didn’t create default one. While creating object you are invoking default one, which doesn’t exist in class code. Then the code gives an compilation error.

vishal surase
  • 51
  • 1
  • 2
0

When you create a new Module object, java compiler add a default constructor for you because there is no constructor at all.

class Module{} // you will never see the default constructor

If you add any kind of constructor even and non-arg one, than java thing you have your own and don't add a default constructor anymore.

This is an non-arg constructor that internelly call the super() constructor from his parent class even you don't have one. (if your class don't have a parent class than Object.Class constructor will be call)

    class Module{

        Module() {} // this look like a default constructor but in not. 
    }
Java bee
  • 2,522
  • 1
  • 12
  • 25
-2

A default constructor does not take any arguments:

public class Student { 
    // default constructor
    public Student() {   

    }
}
Vogel612
  • 5,620
  • 5
  • 48
  • 73
-3

I hope you got your answer regarding which is default constructor. But I am giving below statements to correct the comments given.

  • Java does not initialize any local variable to any default value. So if you are creating an Object of a class it will call default constructor and provide default values to Object.

  • Default constructor provides the default values to the object like 0, null etc. depending on the type.

Please refer below link for more details.

https://www.javatpoint.com/constructor

Chirag Nimavat
  • 165
  • 2
  • 4