Constructors are used to initialize an object as soon as it is created. Every time an object is created using the ‘new’ keyword, a constructor is invoked. If no constructor is defined in a class, java compiler creates a default constructor. Constructors are similar to methods but with to differences, constructor has the same name as that of the class and it does not return any value.
The types of constructors are:
1. Default constructor
2. Constructor with no arguments
3. Parameterized constructor
4. Copy constructor
1. Default constructor: Java automatically creates default constructor if there is no default or parameterized constructor written by user. Default constructor in Java initializes member data variable to default values (numeric values are initialized as 0, Boolean is initialized as false and references are initialized as null).
class test1 {
int i;
boolean b;
byte bt;
float ft;
String s;
public static void main(String args[]) {
test1 t = new test1(); // default constructor is called.
System.out.println(t.i);
System.out.println(t.s);
System.out.println(t.b);
System.out.println(t.bt);
System.out.println(t.ft);
}
}
2.Constructor with no arguments: Such constructors does not have any parameters. All the objects created using this type of constructors has the same values for its datamembers.
Eg:
class Student {
int roll_no;
String name;
Student() {
roll_no = 50;
name="ABC";
}
void display() {
System.out.println("Roll no is: "+roll_no);
System.out.println("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student();
s.display();
}
}
3. Parametrized constructor: Such constructor consists of parameters. Such constructors can be used to create different objects with datamembers having different values.
class Student {
int roll_no;
String name;
Student(int r, String n) {
roll_no = r;
name=n;
}
void display() {
System.out.println("Roll no is: "+roll_no);
System.out.println("Name is : "+name);
}
public static void main(String a[]) {
Student s = new Student(20,"ABC");
s.display();
}
}
4.Copy Constructor : A copy constructor is a constructor that creates a new object using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument. This constructor takes a single argument whose type is that of the class containing the constructor.
class Rectangle
{
int length;
int breadth;
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
length = obj.length;
breadth= obj.breadth;
}
public static void main(String[] args)
{
Rectangle r1= new Rectangle(5,6);
Rectangle r2= new Rectangle(r1);
System.out.println("Area of First Rectangle : "+
(r1.length*r1.breadth));
System .out.println("Area of First Second Rectangle : "+
(r1.length*r1.breadth));
}
}