Constructor in Java


Prev Tutorial Next Tutorial

Constructor in Java

constructor in Java is a special member method which will be called implicitly (automatically) by the JVM whenever an object is created for placing user or programmer defined values in place of default values. In a single word constructor is a special member method which will be called automatically whenever object is created.

The purpose of constructor is to initialize an object called object initialization. Constructors are mainly create for initializing the object. Initialization is a process of assigning user defined values at the time of allocation of memory space.

Syntax

className()
{
.......
.......
}

Advantages of constructors in Java

  • A constructor eliminates placing the default values.
  • A constructor eliminates calling the normal or ordinary method implicitly.

How Constructor eliminate default values ?

Constructor are mainly used for eliminate default values by user defined values, whenever we create an object of any class then its allocate memory for all the data members and initialize there default values. To eliminate these default values by user defined values we use constructor.

How Constructor eliminate default values

Example

class Sum
{
int a,b;
Sum()
{
a=10;
b=20;
}
public static void main(String s[])
{
Sum s=new Sum();
c=a+b;
System.out.println("Sum: "+c);
}
}

Output

Sum: 30

In above example when we create an object of "Sum" class then constructor of this class call and initialize user defined value in a=10 and b=20. if we can not create constructor of Sum class then it print " Sum: 0 " because default values of integer is zero.

Rules or properties of a constructor

  • Constructor will be called automatically when the object is created.
  • Constructor name must be similar to name of the class.
  • Constructor should not return any value even void also. Because basic aim is to place the value in the object. (if we write the return type for the constructor then that constructor will be treated as ordinary method).
  • Constructor definitions should not be static. Because constructors will be called each and every time, whenever an object is creating.
  • Constructor should not be private provided an object of one class is created in another class (Constructor can be private provided an object of one class created in the same class).
  • Constructors will not be inherited from one class to another class (Because every class constructor is create for initializing its own data members).
  • The access specifier of the constructor may or may not be private.
  1. If the access specifier of the constructor is private then an object of corresponding class can be created in the context of the same class but not in the context of some other classes.
  2. If the access specifier of the constructor is not private then an object of corresponding class can be created both in the same class context and in other class context.

Difference between Method and Constructor

MethodConstructor
1Method can be any user defined nameConstructor must be class name
2Method should have return typeIt should not have any return type (even void)
3Method should be called explicitly either with object reference or class referenceIt will be called automatically whenever object is created
4Method is not provided by compiler in any case.The java compiler provides a default constructor if we do not have any constructor.

Types of constructors

Based on creating objects in Java constructor are classified in two types. They are

  • Default or no argument Constructor
  • Parameterized constructor.

Default Constructor

A constructor is said to be default constructor if and only if it never take any parameters.

If any class does not contain at least one user defined constructor than the system will create a default constructor at the time of compilation it is known as system defined default constructor.

Syntax

class className
{			    
.....	// Call default constructor
clsname ()
{
Block of statements;  // Initialization
}
.....
}

Note: System defined default constructor is created by java compiler and does not have any statement in the body part. This constructor will be executed every time whenever an object is created if that class does not contain any user defined constructor.

Example of default constructor.

In below example, we are creating the no argument constructor in the Test class. It will be invoked at the time of object creation.

Example

//TestDemo.java
class Test
{
int a, b;
Test ()
{
System.out.println("I am from default Constructor...");
a=10;
b=20;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
};
class TestDemo
{
public static void main(String [] args)
{
Test t1=new Test ();
}
};

Output

Output:
I am from default Constructor...
Value of a: 10
Value of b: 20

Rule-1:

Whenever we create an object only with default constructor, defining the default constructor is optional. If we are not defining default constructor of a class, then JVM will call automatically system defined default constructor. If we define, JVM will call user defined default constructor.

Purpose of default constructor?

Default constructor provides the default values to the object like 0, 0.0, null etc. depending on their type (for integer 0, for string null).

Example of default constructor that displays the default values

class Student
{
int roll;
float marks;
String name;
void show()
{
System.out.println("Roll: "+roll);
System.out.println("Marks: "+marks);
System.out.println("Name: "+name);
}
}
class TestDemo
{
public static void main(String [] args)
{
Student s1=new Student();
s1.show();
}
}

Output

Roll: 0
Marks: 0.0
Name: null

Explanation: In the above class, we are not creating any constructor so compiler provides a default constructor. Here 0, 0.0 and null values are provided by default constructor.

parameterized constructor

If any constructor contain list of variable in its signature is known as paremetrized constructor. A parameterized constructor is one which takes some parameters.

Syntax

class ClassName
{
.......
ClassName(list of parameters) //parameterized constructor
{
.......
}
.......
}

Syntax to call parametrized constructor

ClassName  objref=new ClassName(value1, value2,.....);
		OR
new ClassName(value1, value2,.....);		

Example of Parametrized Constructor

class Test
{
int a, b;
Test(int n1, int n2)
{
System.out.println("I am from Parameterized Constructor...");
a=n1;
b=n2;
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
};
class TestDemo1
{
public static void main(String k [])
{
Test t1=new Test(10, 20);
}
};

Important points Related to Parameterized Constructor

  • Whenever we create an object using parameterized constructor, it must be define parameterized constructor otherwise we will get compile time error. Whenever we define the objects with respect to both parameterized constructor and default constructor, It must be define both the constructors.
  • In any class maximum one default constructor but 'n' number of parameterized constructors.

Example of default constructor, parameterized constructor and overloaded constructor

Example

class Test
{
int a, b;
Test ()
{
System.out.println("I am from default Constructor...");
a=1;
b=2;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
Test (int x, int y)
{
System.out.println("I am from double Paraceterized Constructor");
a=x;
b=y;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
Test (int x)
{
System.out.println("I am from single Parameterized Constructor");
a=x;
b=x;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
Test (Test T)
{
System.out.println("I am from Object Parameterized Constructor...");
a=T.a;
b=T.b;
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
};
class TestDemo2
{
public static void main (String k [])
{
Test t1=new Test ();
Test t2=new Test (10, 20);
Test t3=new Test (1000);
Test t4=new Test (t1);
}
};

Note By default the parameter passing mechanism is call by reference.

Constructor Overloading

Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking the number of parameters, and their type.
In other words whenever same constructor is existing multiple times in the same class with different number of parameters or order of parameters or type of parameters is known as Constructor overloading.
In general constructor overloading can be used to initialized same or different objects with different values.

Syntax

class  ClassName
{
ClassName()
{
..........
..........
}
ClassName(datatype1 value1)
{.......}
ClassName(datatype1 value1, datatype2 value2)
{.......}
ClassName(datatype2 variable2)
{.......}
ClassName(datatype2 value2, datatype1 value1)
{.......}
........
}

Why overriding is not possible at constructor level.

The scope of constructor is within the class so that it is not possible to achieved overriding at constructor level.


Prev Tutorial Next Tutorial

Advertisements




Facebook Likes

Advertisements