Question

Which of the below classes will use a default constructor, when we initialize an object from them?

class X {}

class Y {

    Y () {}

}

class Z {

    Z(int i ) {} 

}

class Z will not use a default constructor. class X will use a default constructor.

But what about Y? is a user defined empty constructor called a default constructor? Like they say on wikipedia (Java section) http://en.wikipedia.org/wiki/Default_constructor

Or should there be no constructor defined in the class when we can speak of a default constructor when initializing an object?

Was it helpful?

Solution 2

If you have define a empty argument constructor to a Class, then user defined empty argument constructor will replace default constructor which generated by compiler.

The default constructor is the no-argument constructor automatically generated unless you define another constructor with no argument. Check JLS 8.8.9 for more details

is a user defined empty constructor called a default constructor?

No, It's called used defined constructor.

Or should there be no constructor defined in the class when we can speak of a default constructor when initializing an object?

Default constructor mean, Compiler generated, no argument constructor. Every other Constructors are called used defined constructors.

OTHER TIPS

The "default" constructor is the no-args (no arguments) constructor.

If you don't declare any constructors, an implicit no-args constructor will be defined.

If you declare any constructors, the implicit no-args constructor is not defined.

A constructor is always called when constructing a new object, and a constructor of every superclass of the class is also called. If no constructor is explicitly called, the default constructor is called (which may or may not be declared).

DefaultConstructor JLS

The default constructor is the one Java provides by default. Anything you write explicitly is not a default.

Default Constructor comes in to picture then and then only,

When You haven't provide any constructors for your class

Prefer to read :Providing Constructors for Your Classes

You don't have to provide any constructors for your class, but you must be careful when doing this. 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.

If you don't define any constructor default constructor will come in to the scene. every other case you have to go with what ever the define constructors.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top