Java default constructor
Asked Answered
H

13

193

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;
}
Hyacinthie answered 20/12, 2010 at 10:24 Comment(0)
B
306

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.

See the Java specifications, specifically: Section 8.8.9. Default Constructor of Java Language Specification.

If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:

  • The default constructor has the same access modifier as the class, unless the class lacks an access modifier, in which case the default constructor has package access (§6.6).
  • The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3).
  • The default constructor has no throws clause.

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.
Bilabial answered 20/12, 2010 at 10:29 Comment(19)
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.Pyriphlegethon
Everything that the default constructor does will be done for constructors that don't do those things themselves.Bilabial
@Bilabial Where do you see in the specification the statement that the user defined nullary constructor without parameters is not called the default constructor?Pumping
@ŁukaszRzeszotarski where do you see anything that suggests otherwise? Occam's razor.Bilabial
@Bilabial 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]'Pumping
You should read and provide Wikipedia's sources, not Wikipedia itself.Bilabial
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.Voroshilov
@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.Likeness
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.Powered
maybe we can call this default(synthesized) default-constructor. For me, default constructor is just a constructor callable with no argument.Distress
@Gab是好人 what it is for you does not make it true.Bilabial
@Bilabial then how do you call a user-defined no-argument constructor?Distress
@Gab是好人 it's called a "no-argument" or "no-arg" constructor.Bilabial
@Bilabial OK, I agree. I used the C++ way to call the Java default constructor.Distress
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 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"Webbing
From 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.Winnebago
@muzimuzhiZ did you finish reading the answer?Bilabial
@Bilabial my badWinnebago
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."Jackal
F
42

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(){
}
For answered 20/12, 2010 at 10:27 Comment(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!Fissirostral
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).Viveca
@Sergey This seems to disagree download.oracle.com/javase/tutorial/java/javaOO/… as does wikipedia.For
as does the Java Language Specification! I didn't realize there was such a difference between Java and C++ in terminology.Ammoniac
Y
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...

Younglove answered 20/12, 2010 at 10:50 Comment(0)
N
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.

Narcotize answered 11/12, 2013 at 11:28 Comment(0)
J
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());
    }
}
Jarvey answered 17/8, 2012 at 9:42 Comment(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.Crawford
@Israelg99 What is the exact terminology when we use this(10,10,10); ?Margarettemargarida
@Israelg99 never mind, it is called explicit constructor invocation ref: docs.oracle.com/javase/tutorial/java/javaOO/thiskey.htmlMargarettemargarida
P
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.

Pyriphlegethon answered 12/9, 2013 at 14:25 Comment(0)
U
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
Unsnarl answered 28/4, 2017 at 21:37 Comment(7)
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.Mystify
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.Unsnarl
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.Mystify
Thanks for your comment. I don't mean that. Now edited.Unsnarl
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.Mystify
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.Unsnarl
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!Mystify
F
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.

Frieder answered 13/12, 2013 at 10:9 Comment(6)
Constructor duty is to initialize memory space, in which the object is created. The object initialization is Java Virtual Machine responsibility.Wanderjahr
@StephenC not according to this articleWanderjahr
@Wanderjahr - 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.Mystify
@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.Wanderjahr
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.Mystify
References to read: docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.5 and docs.oracle.com/javase/specs/jvms/se8/html/… ... noting what it says about constructor invocation ... and docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.9Mystify
T
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.

Throughput answered 21/6, 2016 at 7:43 Comment(0)
S
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.

Sycophant answered 18/2, 2020 at 12:48 Comment(0)
B
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. 
    }
Bellhop answered 29/4, 2020 at 12:42 Comment(0)
F
-2

A default constructor does not take any arguments:

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

    }
}
Frogfish answered 20/12, 2010 at 10:34 Comment(1)
This is wrong, this is a non-arg constructor, not a default constructor.Conquer
S
-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

Saxecoburggotha answered 31/10, 2017 at 16:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.