Initializing a variable is considered very helpful while making programs. We can initialize variables of primitive types at the time of their declarations. For example:
int a =10;
In Object Oriented Programming language (OOPL) like Java, the need of initialization of fields of a new object is even more common. We have already done this using two approaches.
In the first approach, we used a dot operator to access and assign values to the instance variables individually for each object. However, it can be a tedious job to initialize the instance variables of all the objects individually. Moreover, it does not promotes data hiding.
r1.length =5;
r2.length =7;
Where r1,r2 are objects of a Rectangle class.
In another approach, we made use of method setData() to assign values to fields of each object individually. But it would have to be called explicitly for each object. This would become inconvenient if the number of objects are very large.
r1.setData(5,6);//sets length and breadth of r1 Rectangle object
r2.setData(7,8);
The above two approaches does not simulate the problem properly. A better solution to the above problem is to initialize values to the object at the time of its creation in the same way as we initialize values to a variable of primitive data types. This is accomplished using a special method in Java known as constructor that enables an object to initialize itself at the time of its creation without the need to make separate call to the instance method.
A constructor is a special method that is called whenever an object is created using the new keyword. It contains a block of statements that can be used to initialize instance variables of an object before the reference to this object is returned by new. A constructor does look and feel a lot like a method but it is different from a method generally in two ways.
Constructors look much like Java instance methods, but they are not methods because a constructor does not contain any return type, nor even void. Constructors and methods are different, but you often hear people refer to constructors as particular methods.
Note: Each class must have a constructor, be it a normal or an abstract class.
A constructor always has the same name as the class whose instance members they initialize. It is because the constructor is automatically called by the compiler whenever an object of a class is created.
The main purpose of a constructor is to initialize a new object. Java does not allocates memory for objects at application startup time but rather when the instance is created by keyword new. When new is invoked, Java allocates enough memory to hold the object and then initializes any instance variables to default values.
Any access specific may use with a constructor, and they can also declare as private constructors. However, although these are entirely possible in the Java language, it must be borne in mind that a private constructor only has scope within the class.
• The initial statement in any constructor code must be this() or super(). If you omit these, an error exception is thrown by the compiler.
• It is possible to overload a constructor but not to override one.
• Constructors may not be inherited.
• An interface does not have a constructor.
• An abstract class may have a constructor, and it may be invoked when the class instantiates, so long as it is the class that implements an interface.
• With this() keyword, one constructor can invoke other constructors of the same class.
The syntax for constructor is as follows.
constructorName([parameterList]){
//Constructor Body
}
Here, the ConstructorName is same as the class name it belongs to.
The parameterList is the list of optional zero or more parameter(s) that is specified after the classname in parentheses. Each parameter specification, if any, consists of a type and a name and are separated from each other by commas.
Now let us consider a program
// use of Constructor
Class Rectangle{
int length;
int breath;
Rectangle(){ length =5; breath =6;}
int area(){int rectArea = length * breath; Return rectArea;}
}
Class Constructordemo {
Public static void main(String args[]){
Rectangle firstRect =new Rectangle();
System.out.println(“Area of Rectangle= ”+ firstrect.area());
}
}
Output: Area of rectangle = 30
Explanation : In this program, when the statement
Rectangle firstRect = new Rectangle();
is executed, the new operator creates a new but uninitialized object of the class. Then the constructor (Rectangle ()) is called and the statements in its body are executed. As a result, the instance variables length and breadth of object firstRect will be initialized to integer literals 5 and 6 respectively.
Then the address of the allocated Rectangle object is returned and assigned to the reference variable firstRect. This method of initializing instance variable(s) of an object(s) using constructor is very simple and concise as there is no need to explicitly call the method for each object separately.
Different Constructor Types
1) Default Constructor: Each time an object is created, a constructor is always invoked. In the above program, the constructor we created was invoked. But in the programs that we made earlier, we did not create any constructor. So in such situations, the compiler automatically writes one for you. This constructor is known as the default constructor. It does not contain any parameters nor does it contain any statements in its body. Its only purpose is to enable you to create object of class type. The default constructor looks like
public Rectangle(){ }
When the compiler creates a default constructor; it does nothing. The objects created by the default constructor will have fields with their default values.
It should be remembered that constructors are invoked only after the instance variables of a newly created object of the class have been assigned their default initial values and after their explicit initializers are executed.
2) no-arg Constructor: A no-arg constructor is a constructor that contains no arguments. The no-arg constructor signature is identical to that of the default constructor, but the body of this constructor may contain code – the default constructor body is always left empty. There are those who swear blind that the default and the no-arg constructor are identical, but they are not. If, for example, you were to add public Demo() to a class called Demo(), it is not a default constructor because it contains code. Here’s an example:
class Demo {
public Demo(){
System.out.println(“This is an example of a no-arg constructor”);
}
public static void main(String args[]){
new Demo();
}
}
3) Parameterized Constructor: Unlike default constructor which do not have any parameters, it is however possible to have one or more parameters in a constructor. This type of constructor which have parameters is known as parameterized constructor. Using parameterized constructor, it is possible to initialize objects with different set of values at the time of their creation. These different set of values initialized to objects must be passed as arguments when constructor is invoked. The parameter list can be specified in the parentheses in the same way as parameter list is specified in the method.
In order to understand the concept of parameterized constructor, let us again consider the Rectangle class in which we defined a zero parameter constructor to assign the same set of values to all the objects of the Rectangle class. But if we want to create objects of Rectangle class and initialize different set of values then we need to create a parameterized constructor as illustrated in the following program.
class Rectangle{
int length;
int breadth;
Rectangle(int l,int b){ length = l; breath = b;}
int area(){ return(length * breath);}
class ParaConstructor {
public static void main(String[] args){
Rectangle firstRect = new Rectangle(5,6);
Rectangle secondRect = new Rectangle(7,8);
System.out.println(“Area of first rectangle =“+firstRect.area());
System.out.println(“Area of second rectangle=“+secondRect.area());
}
}
4) Copy Constructor: This is also Another type of Constructor. In Constructor object of another Constructor is passed As name Suggests you Copy means Copy values of another Class object This is used for Copying the values of class object into an another object of class So For Calling Copy Constructor We have to pass the name of object whose values we wants to Copying .
5) Chaining Constructors: When one constructor calls for another constructor of an identical class, we call this constructor chaining. The purpose of this is to allow you to pass your parameters through several different constructors while doing the initialization in one place. If we have two constructors that need a specific parameter and you do n’t chain the constructors, that parameter needs to initialized twice; when there are changes to that initialization, you then need to repeat those changes in all the relevant constructors, not just one.
In general, the constructor that has the fewest arguments should call the constructors that have more. Let’s see an example to try to understand this.
We have some constructors in this example; one calls another using this keyword. The very first statement in the constructor must be this(); if it isn’t, you will get an error message telling you there is an “Exception in thread “main” java.lang.Error: Unresolved compilation problem: Constructor call must be the first statement in the construct”.
class Employee {
public String empName;
public int empSalary;
public String address;
//The default constructor for the class
public Employee() {
//this calls the constructor that has the String parameter
this(“Thakur”);
}
public Employee(String name) {
//this will call the constructor that has the (String, int) parameter
this(name, 152116);
}
public Employee(String name, int sal) {
//this will call the constructor that has the (String, int, String) parameter
this(name, sal, “Punjab”);
}
public Employee(String name, int sal, String addr) {
this.empName=name;
this.empSalary=sal;
this.address=addr;
}
void disp() {
System.out.println(“Employee Name: “+empName);
System.out.println(“Employee Salary: “+empSalary);
System.out.println(“Employee Address: “+address);
}
public static void main(String[] args) {
Employee obj = new Employee();
obj.disp();
}
}
The output of this will be:
Employee Name: Thakur
Employee Salary: 152116
Employee Address: Punjab
Destructor:
1. It is a member function whose name is same as the class. But preceded by a ~ (tilde) symbol.
2. It has no return type.
3. It cannot have parameters.
4. It is implicitly called when object is no longer required.
5. It is used to release the memory and close files and database conversions.
( No Destructor concept in java )
Note :- java does not support destructor. But it is supported by C,C++.