Page 256 - Computer science 868 Class 12
P. 256
The output of the preceding program is as follows:
if s1="India", s2="New Delhi"
//Output
Not Equal
8.12 CONSTRUCTOR
Constructor is a member method with the same name as that of the class. It used to initialise the instance variables
of the objects.
Syntax of defining a constructor is as follows:
class <name of class>
{
Data members……
<name of class>() //constructor
{ job of the constructor, i.e., initialising the data members}
<member methods>()
{ Job of the method }
public static void main()
{
<name of class> <name of object> = new <name of class>();
<name of object>.<member method>();
}
}
Constructors have the following characteristics:
1. The name of the constructor is the same as the name of the class.
2. Constructors are used to initialise the instance variables of the objects.
3. Constructors do not have any return type, not even void.
4. Constructors are always public, i.e., they can be called from outside the class while creating the object.
5. Constructors are automatically invoked while creating the object.
6. A single class can have more than one constructor. Thus, constructors can be overloaded automatically.
8.12.1 Types of Constructors
There are four types of constructors as follows:
1. Default constructor: In a class and object program, if the constructor is not mentioned, then the compiler calls the
default constructor which assigns all the data members of the class to their default values.
2. No-Argument constructor: When no argument is passed to the constructor, then the constructor is known as
no-argument non-parameterised constructor.
3. Parameterised constructor: When arguments are passed to the constructor, then the constructor is known as
Parameterised Constructor.
4. Copy Constructor: The Copy Constructor is a special type of constructor which is used to create an object by
initialising it with earlier created object of the same class. Thus, in one word it duplicates an object.
254254 Touchpad Computer Science-XII

