190

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;
}
0

13 Answers 13

304

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.
19
  • 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. Sep 12, 2013 at 14:01
  • 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? Sep 13, 2013 at 5:32
  • 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 2, 2013 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, 2014 at 8:38
  • 2
    @Gab是好人 it's called a "no-argument" or "no-arg" constructor.
    – OrangeDog
    Apr 13, 2017 at 15:00
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(){
}
4
  • 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, 2010 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). Dec 20, 2010 at 10:30
  • 8
    @Sergey This seems to disagree download.oracle.com/javase/tutorial/java/javaOO/… as does wikipedia.
    – Jim
    Dec 20, 2010 at 10:32
  • 5
    as does the Java Language Specification! I didn't realize there was such a difference between Java and C++ in terminology. Dec 20, 2010 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...

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.

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());
    }
}
3
  • 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, 2015 at 23:48
  • @Israelg99 What is the exact terminology when we use this(10,10,10); ?
    – sgiri
    Aug 31, 2017 at 10:45
  • @Israelg99 never mind, it is called explicit constructor invocation ref: docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
    – sgiri
    Aug 31, 2017 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.

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
7
  • 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, 2017 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, 2017 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, 2017 at 21:48
  • Thanks for your comment. I don't mean that. Now edited.
    – Yergalem
    May 21, 2017 at 1: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, 2017 at 2:13
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.

6
  • Constructor duty is to initialize memory space, in which the object is created. The object initialization is Java Virtual Machine responsibility.
    – MaxZoom
    Apr 17, 2015 at 21:03
  • @StephenC not according to this article
    – MaxZoom
    May 23, 2017 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, 2017 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, 2017 at 2: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, 2017 at 2:49
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.

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.

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. 
    }
-2

A default constructor does not take any arguments:

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

    }
}
1
  • 5
    This is wrong, this is a non-arg constructor, not a default constructor.
    – Tom
    Dec 15, 2016 at 15:28
-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

Not the answer you're looking for? Browse other questions tagged or ask your own question.