Constructor
Constructor
Brajesh Raj
Index
introduction
Types of constructors
◦ Default Constructor
◦ Parameterized Constructor
Constructor Overloading
Does constructor return any value?
Copying the values of one object into another
Does constructor perform other tasks instead
of the initialization
Introduction
In Java, a constructor is a block of codes similar to the method. It is
called when an instance of the class is created. At the time of calling
constructor, memory for the object is allocated in the memory.
Every time an object is created using the new() keyword, at least one
constructor is called. It calls a default constructor if there is no
constructor available in the class. In such case, Java compiler provides a
default constructor by default.
A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.
A constructor must not have a return type. A method must have a return type.
The constructor name must be same as the The method name may or may not be same as
class name. the class name.
Java Copy Constructor
There is no copy constructor in Java.
However, we can copy the values from one
object to another like copy constructor in
C++.
There are many ways to copy the values of
one object into another in Java. They are:
◦ By constructor
◦ By assigning the values of one object into another
◦ By clone() method of Object class
copy the values of one object into
another using Java constructor
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}