Constructors 1
Constructors 1
Definition
class Test
{
// body of constructor
Invoking a constructor
Constructors are invoked automatically when we create objects for the class.
Syntax:
Example:
Constructors name must be similar to that of the class name inside which it
resides.This allows the constructors to be invoked automatically on object
creation.)
Constructors are automatically(implicitly) called when an object is created.
Types of constructors
a) Parameterised constructor
b) Non Parameterised constructor
c) Default constructor
d) Copy constructor
Parameterised constructor
Class student
int regno;
String name;
char section;
float average;
regno =x;
name = y;
section=z;
average=f;
}
Void display ()
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(f);
Stu.display();
}}
Program differently to understand that compiler creates its own object( Page 397)
A constructor which initialises the instance variables with definite values readily
available within it is called as non – parameterised constructor.
Class student
{
int regno;
String name;
regno =10;
name = “Sheela”;
Void display ()
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(f);
Stu.display();
}}
Default constructor:
The constructor which is used to initialise the data members with default
initial values(0,null,empty values) is called as default constructor.
We need not explicitly define a default constructor as the compiler will
supply a default constructor.
Class student
int regno;
String name;
char section;
float marks;
Void display ()
System.out.println(regno);
System.out.println(name);
System.out.println(section);
System.out.println(marks);
Stu.display();
}}
Output:
Null
(empty )
0.0
Note :
Copy constructor
2 Types
Example:
class copycon
{
a=x;
Here object is passed to the constructor and the instance variables of current object
are initialised by copying the values from object passed to the constructor.
Example:
class copycon
{
a=x;
a=ob.a;
use of constructors
Constructor overloading.
It is the process of using a number of constructors with the same name but
having different parameter list.
The compiler differentiates the constructor by taking into account the
number of parameters in the list and their type.
If a class contains more than one constructors then they are overloading
constructor.
Example:
class copycon
a=10;
a=x;
a=ob.a;
Page 401