Constructors

<< Previous Chapter Next Chapter >>
Constructor in Java:

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();
            }
}
Output:



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:

Note: there is no copy constructor in java, it is only available in C++.

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
      }

}

Error:


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();
      }
}

Output:




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();
      }
}

Output:



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.

No comments:

Post a Comment