Constructors in Java
Constructors in Java
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 :
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);
}
}
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.
}
}
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.