Page 119 - 2617_JSSPS_C-7
P. 119
<member methods>()
Definition
{
A constructor is a method that has the
Job of the method
same name of the class and used for
}
initialising an object.
}
Let us take an example.
class book
{
String name;
int no_page;
double price;
book() // Constructor
{
name= ""; // initializing null to name
no_page=0; // initializing 0 to no_page
price=0.0; // initializing 0.0 to price
}
…
…
…
}
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();
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.
Java Programming 117

