Page 300 - CA_Blue( J )_Class10
P. 300
book() // Constructor
{
name= ""; // initializing null to name
no_page=0; // initializing 0 to no_page
price=0.0; // initializing 0.0 to price
}
…
…
…
}
12.1.1 How to Call a Constructor?
As we know that a method can be invoked separately. But a constructor cannot be invoked separately. Every time when
an object of a class is created, constructor of the class is called. For example:
<name of class> <name of object> = new <constructor> ();
If we want to invoke constructor of the above example,
book ob = new book();
12.1.2 Characteristics of a Constructor
Following are the characteristics of a constructor:
• Name of the constructor must be same as the name of the class.
• Constructors are used to initialize the instance variables of the class.
• Constructor do not have any return type, not even void.
• Constructors are always public as they can be called from outside the class while creating the object of the class.
• Constructors are automatically invoked while creating the object.
12.2 DIFFERENT TYPES OF CONSTRUCTORS
In Java, there are four different types of constructors which are default, non-parameterised, parameterised and copy
constructors.
12.2.1 Default Constructor
If a constructor is not defined in a class, then the Java compiler provides a constructor which is known as default
constructor. It does not have any parameter and statements in its body. For example:
class demo
{
public demo() //default constructor
{
}
}
A default constructor is used to initialize the instance variables automatically with default values. For example, int is
initialized by 0, double is initialized by 0. String is initialized by null. Let us take an example given below:
1 class default_cons
2 {
3 int a;
4 double b;
5 String s;
6 void print()
298298 Touchpad Computer Applications-X

