Constructor in Java:
Before defining constructors lets discuss about few backgrounds:
Before defining constructors lets discuss about few backgrounds:
A constructor is a special method which gets invoked while object creation.
Initialization – it means at the time of born, putting some value in variable (while defining first value) not after variable is defined and load into memory. In other words putting any values in data members while defining objects is known as initialization.
For example – a company recruits 50 fresher employees and decided to keep their initial salary to be 15000/- per month then the simple solution is to put 15000 as a default initial value in salary data member of each objects.
Other example – a database connectivity code or network connectivity code required only once for an application which means we can put this code in constructor while object creation.
By default java puts some value in any variables.
As a real example a newly born baby needs some vaccination only once when they born, or other example when we purchase a pant we mostly required to short its length.
Class Temp
{
Temp()
{
System.out.println(this);
}
public static void main(String args[])
{
Temp t = new Temp();
System.out.println(t);
}
In constructor concept “this” plays a major role. “this” is implicitly passed to the constructor and returned back at last to the method where object is created. In above program “this” is returned bacl from constructor to main method.
Type of constructors:
There are 2 types of constructors in java:
1) Default constructor – constructor with no arguments Example:
public class Temp
{
Temp()
{
System.out.println("Temp is a default constructor!");
}
public static void main(String args[])
{
Temp t = new Temp();
}
2) Parameterized constructor – constructor with some arguments.
public class Temp
{
int age;
String name;
double salary;
Temp(String name, int age, double salary)
{
this.name = name;
this.age = age;
this.salary = salary;
}
public static void main(String args[])
Temp t = new Temp("Akhilesh", 24, 30000);
System.out.println("My Name: " + t.name + ", Age: " + t.age
+ ", Salary: " + t.salary);
}
}
Output:
Output:
Quick Question – why technologist has put its name as constructor only, not anything else?
Answer – because it is the one who creates or constructs.
Quick Question – constructor is static or non static?
Answer – constructor is always static because we never call it using any object of the class, instead it is actually creates the object.
Quick Question – let’s take a small example:
class Temp2
{
void show()
{
System.out.println("Show");
}
public static void main(String args[])
{
Temp2 obj = new Temp2(); //line no 9
}
}
In above program at line number 9 the compiler will try to find method name Temp2(), as we claim that constructor is a special method, so are we expecting a not found error here?
Answer – No error or exception, because if user has not declared any constructor in the class, the compiler creates a default constructor implicitly. No single class can exists without constructor. If we write a parameterized constructor explicitly then compiler will not create any implicit default constructor and will throw exception. For example:
class Temp2
{
void show()
{
System.out.println("Show");
}
Temp2(String name)
{
System.out.println(“My Name: “ + name);
}
public static void main(String args[])
{
Temp2 obj = new Temp2(); //line no 9
}
}
Quick Question – When we should create a default and when we should create a parameterized constructor?
Answer – When we want to initialize the data member of each object with same default value then we should always prefer the default constructor, this concept is known as static initialization of non static data members.
Rule: whenever we want to initialize the data member of each object with different values then always use parameterized constructor and this concept is known as dynamic initialization of non static data members.
Code Example – Static initialization:
public class Temp {
int age;
double salary;
Temp() {
this.age = 20;
this.salary = 15000;
}
void show()
{
System.out.println("Age: " + age + ", Salary: " +salary);
}
public static void main(String args[]) {
Temp t1 = new Temp();
t1.show();
Temp t2 = new Temp();
t2.show();
}
}
Code Example – Dynamic initialization:
public class Temp {
int age;
double salary;
Temp(int age, double salary) {
this.age = age;
this.salary = salary;
}
void show()
{
System.out.println("Age: " + age + ", Salary: " +salary);
}
public static void main(String args[]) {
Temp t1 = new Temp(24, 30000);
t1.show();
Temp t2 = new Temp(20, 15000);
t2.show();
}
}
Alternate of Copy Constructor:
A constructor which creates a new object exactly same as existing object is known as copy constructor.
As a real example mark sheet is an original object, photo copy is a duplicate object and photo copy machine is a copy constructor.
There is no existence of copy constructor in java; however we can perform similar type of operation, for example:
public class Temp
{
int x, y;
Temp(int x, int y)
{
this.x = x;
this.y = y;
}
Temp(Temp z)
{
this.x = z.x;
this.y = z.y;
}
void show()
{
System.out.println("x = " + x + ", y =" + y);
}
public static void main(String args[])
{
Temp temp1 = new Temp(10,20);
temp1.show();
Temp temp2 = new Temp(temp1); //line #24
temp2.show();
}
}
Output:
But above program is clearly not a copy constructor, because copy construct means copy the object when it is loaded into the memory, not after it’s created and loaded.
In above example at line number 24 the reference of object temp1 is passed to the constructor as a call by value.
Quick Question – Java supports call by value or call by reference?
Answer – Java only support call by value because until we pass the address the call by reference cannot be achieved. So, we just call it as we are passing the reference but actually we pass the value.
Constructor Chaining:
Constructor chaining is the process where a constructor is called from another constructor. We have to use “this” keyword to achieve the constructor chaining. There is a hard rule that in case of constructor chaining the “this” keyword should always be the first statement.
An Example:
public class Temp
{
Temp() //line #3
{
this(10);
System.out.println("First default constructor.");
}
Temp(int x) //line #8
{
this(10, 20);
System.out.println("Second single parameter constructor. "
+ x);
}
Temp(int x, int y) //line #13
{
System.out.println("Third constructor with 2 parameters " +
x + " & " + y);
}
public static void main(String args[])
{
new Temp();
}
}
In above example the first constructor at line no 3 calls second constructor using “this” keyword, then before executing the statements inside this constructor it goes to the called constructor which is second one. Further second constructor invokes third one in similar way.
Note: Whenever we are achieving constructor chaining using “this”, we must skip “this” in at least one constructor otherwise it will go to infinite execution.
Quick Question – In constructor chaining why we use “this” to call a constructor, can’t we use the constructor name directly?
Answer – No, because if any method exists in class with the class name then compiler will get confused which one to call, the method or the constructor.
Quick Question – why we need constructor chaining?
Answer – when multiple tasks like initialization, database connection, network connectivity etc. then a single constructor will be complex and lengthy and code will be difficult to debug, for this reason we need constructor chaining.
No comments:
Post a Comment