Constructors in Java
Constructors in Java
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.
No Argument Constructor:-
Syntax:
Classname()
{
Initialize values
}
Ex:
Class addition
{
int a,b;
addition()
{
a=10;
b=20;
}
void display()
{
System.out.println(“Result “+(a+b));
}
}
Class student
{
Public static void main(String args[])
{
addition obj=new addition();
obj.display();
}
}
Argument Constructor:-
Syntax:
Classname(parameterlist)
{
Initialize values
}
Ex:
Class addition
{
int a,b;
addition(int x,int y)
{
a=x;
b=y;
}
void display()
{
System.out.println(“Result “+(a+b));
}
}
Class student
{
Public static void main(String args[])
{
addition obj=new addition(10,20);
obj.display();
}
}
Copy Constructor:-
A Constructor that copies values from another object is called “Copy Constructor”
It Copies the values from either “No arugment Constructor” or “ Argument
Constructor”
Some times it copies values from both of them
Here we pass “Object” as a Paramter
It is also used to initialize values for the object
It is Automatically called when we creates the object of class
In this Constructor the programmer must remember name of Constructor is
same as name of class
Copy Constructor never declared with the help of Return Type. Means cant
Declare a Constructor with the help of “void Return Type. “
It is called by the JVM automatically itself whenever the programmer creates an
“Object”.
Syntax:
Classname(classname Object)
{
Initialize values
}
Ex:
Class addition
{
int a,b;
void display()
{
System.out.println(“Result “+(a+b));
}
}
Class student
{
Public static void main(String args[])
{
addition obj1=new addition(10,20);//parameterized constructor
addition obj2=new addition(obj1);//copy constructor
obj1.display();
obj2.display();
}
}
In the above example “addition” is class. When we create object
“obj1” then the “JVM” automatically calls and initializes values in the constructor
“addition(10,20)”. There after those values are copied by another object “obj2” with the
help of “copy Constructor” that is declared at “class addition”.