Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Constructors in Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Constructors in Java

A constructor is a member function of a class with the same name as that of its class name. it is
defined like other member function of a class. It is used to initialize the data member.
Characteristics of constructor:
1. It has same name as the class-name.
2. It cannot have a return type, not even void is used.
3. It gets called automatically whenever an object is created.

use of constructor :
Allocate memory space for an object.
Initialize data members/ instance variable of the class

Types of Constructor :

1. Non Parameterized Constructor


2. Parameterized Constructor

Non Parameterized Constructors : A constructor that accepts no parameters are called non
parameterized constructors, non parameterized constructors that initialize the instance
variables to zero, null and empty values are called Default Constructors.

1. class Constr
{
int n;
Constr( )
{
n = 0;
} // invokes the constructor
public static void main( )
{
Constr obj = new Constr( );
System.out.println(obj.n);
}
}

Parameterized Constructor : A parameterized constructor accepts parameters or


values in its argument list which initialize the various instance data members of the class.
class Constr
{
int n;
Constr(int val)
{
n = val;
} // invokes the constructor
public static void main( )
{ int v = 25;
Constr obj = new Constr(v);
}
}
constructor overloading : When two or more constructor with different function parameter is
defined in a class then it is called constructor overloading.

class Overload
{
int a,b;
Overload()
{
a=10;
b=20;
}
Overload(int x, int y)
{
a=x;
b=y;
}
public static void main()
{
Overload obj1 =new Overload(); //Calls the first constructor version.
Overload obj2 = new Overload(5,8); //Calls the 2rd constructor version.
}
}

Difference between constructor and method :

Constructor Method
Class name and constructor name should Method can have any name following
be same identifier naming rule

It is used only for initializing data member Can do any type of calculation or
printing.

It is not return type It has return type


It is called automatically It has to be called

You might also like