Constructor

Constructor: Constructor is special method of class that is automatically invoked whenever the object is created. It is used to initialize the member variables of object.

Rules to create constructor

  1. Constructor name should exactly match with class name.
  2. Access specifier of constructor could be private/public or protected.
  3. Constructor should not have any return type not even void.
  4. Constructor should not contain any return statement.
  5. Overloading of constructor is allowed.
  6. Implicit return value of constructor is always an object.

Types of constructor

There are only two types of constructor available in java language as given below.

  1. Default Constructor: Constructor with no parameter or zero parameters is known as default constructor.
  2. Parameterized Constructor: Constructor with one or more than one parameters is known as parameterized constructor.

 

Note: copy constructor is not available in java language, but we can perform operation of copy constructor using the parameterized constructor.

Example:

class Data

{

private int a;

public Data()

{

a=10;

}

public Data(int n)

{

a=n;

}

public void show()

{

System.out.println(“Value=”+a);

}

}

class UseMe

{

public static void main(String args[])

{

Data d1=new Data();

Data d2=new Data(100);

d1.show();

d2.show();

}

}

Output:

Value=10

Value=100

In the above example, Data class contain two types of constructor i.e. default and parameterized constructor. Default constructor is initializing the value of member variable ‘a’ by 10 where as parameterized constructor is initializing the value of member variable by the value of given parameter.

During the execution of main program, object d1 will create memory and initialize the value of member variable by executing the default constructor where as object d2 will create memory and initialize the value of member variable by using parameterized constructor.

Note: if constructors are defined in the class then we can access only the defined constructors but if the class is not containing any constructor then we can access default constructor.


Related Post :    Inheritance 
                                    Garbage Collection
                                    Inheritance FAQ

Leave a Reply

Your email address will not be published. Required fields are marked *