What Is a constructor?
constructor in java is a special member method that will be called implicitly(automatically) by the JVM whenever an object is created for placing user or programmer-defined values in the place of default values.
The purpose of a constructor is to initialize an object called an object initialization.
Advantage of constructor
A constructor elimination placing the default values
A constructor eliminates calling the normal or ordinary method implicitly.
Properties of a constructor
constructor name must be similar to the name of the class
the constructor will be inserted when the object is created
constructor has no return even void
the constructor should not be declared static
the constructor will not be inherited
the constructor must be declared as private
the constructor may be overloaded but cannot be overriding
Type of constructor
1 Default constructor
a) system defined
b) user defined
2 parameterised
a) overloading constructor
b) copy constructor
3 private constructor
system-defined default constructor
if any class does not contain at least one user-defined constructor then the system will create a default.
class ABC
{
}
class boss 1
{
public static void main (string args[])
{
abc aa = new abc (); -------> system defined
}
}
User-defined default constructor
A constructor is said to be the default constructor if and only if it never takes any parameters.
parameterized constructor
If any constructor contains a list of variables in its signature is known as parameterized constructor. A parameterized constructor is one that takes some parameters.
overloading constructor
whenever the same constructor is existing multiple times in the same class with a different number of parameters or order of parameters or type of parameter is known as an overloading constructor.
Note:- when we put the return type it changes in the method type
constructor has no return type.
copy constructor
the copy constructor is used to copy one object into another object. In copy constructor argument must be of an object type.
Difference between method and constructor
Method
. method can be any user-defined name
. method should have a return type
. method be called explicitly either with object reference or class reference.
. method is not provided by a compiler in any case.
constructor
. constructor must be of a class name
. It should not have any return type (even void)
. It will be called automatically whenever an object is created
. The java compiler provided a default constructor if class do not have any user-defined a constructor
0 Comments