Constructor Concept Simplified in Java



As we know, all objects we create, must be given some initial values to the variables,they contains.We can do this by using a dot(.) operator to access the instance variables and then assign some values individually.But we really look at this approach, it is very tedious and manual intensive approach to work with the variables individually.Secondly we need to call a method of that class to provide values of the instance variables.
like-obj.setData(10,15);
Java provides a simpler,cleaner and more concise way to initialize the instance variable while creating an object.The way is called use of constructor.
 A constructor is a special method in java which is used to create or construct an instance of a class and initialize the member variables of the newly constructed object.Object construction enables java run time environment to respond to a call(to an object's constructor to create an actual object and store it in memory).  It is called just after the memory allocation for the object.It can be used to initialize the variables of the object to desired values or starting values at the time of object creation.It can be said that an object or instance of a class does not exist in memory until it's constructor is called.

It is not mandatory to provide a constructor for a class.If no user defined constructor is provided,the compiler,during compile time, puts one, called as default constructor and initializes the variable with it's default value.
For numeric data types variables are set to zero(0), for character datatypes the variables are set to '\0' or null,for reference variables are set to null.
Rules for creating constructor:
  1. The constructor name is same as class name
  2. It should not return any value(not even void).
  3. If we are providing argumented constructor, compiler assumes that we know how to use a constructor. Hence it does not put default constructor. We need to provide it.

Example:

class MyDemo()
{
//if we do not mention any constructor the compiler will provide one default constructor
MyDemo()
{
}
}
 
working example:

class MyDemo()
{
int value1;
int value2;
MyDemo()
{
value1=10;
value2=20;
}
public void display(){
System.out.println("Value of Value1"+value1);
System.out.println("Value of Value2"+value2);
}
public static void main(String args[])
{
MyDemo md=new MyDemo();
md.display();
}
}
 
Objective of Constructors:
  1. create instances of a class and store it in memory.
  2. set default values to the variables.
  3. As the constructor does not have return type not even void,when invocation is done,it simply return the reference of the newly created in memory.
  4. The object reference is stored in memory. This gives us a way to 'address' or find our object in memory.Without this reference to this object,we can not call methods in the objects.
Default Constructors:
A default constructor is one which is having no argument.It is used to create "vanilla object".If we create a class with no constructor defined,compiler will automatically create one default constructor.

class HelloWorld{
//no constructor is defined
     public static void print(){
        System.out.println("Hello World");
     }
}
public class DafaultConstructorTest{
    public static void main(String args[])
    {
        HelloWorld hw=new HelloWorld();
//default constructor is called even though we have not created it.
        hw.print();
    }
}
 

Constructor Overloading:
As constructors are methods hence the overloading concept also applies here. A class can have any number of constructors that differ in parameter list.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type. So each of the constructors has some specific objective.In case the constructor is overridden and we want to use the default constructor, in that case, we need to define the default constructor.

public class MyDemo
{
MyDemo(int i)
{
}
MyDemo(float f)
{
}
}
 
In this case if we try to create a vanilla object using new MyDemo(), the compiler will throw an error stating that it can not find the constructor.
Say in the above example we need to create instance with one variable initialized again we need to create instance with two variable initialized,then we will write as below:

public class MyDemo
{
int value1;
int value2;
MyDemo()
{
//default constructor
}
//below are the argumented constructors
MyDemo(int a)
{
value1=a;
}
MyDemo(int a,int b)
{
value1=a;
value2=b;
}
public void display(){
System.out.println("Value of Value1->"+value1);
System.out.println("Value of Value2->"+value2);
}
public static void main(String args[])
{
MyDemo md1=new MyDemo();
md1.display();
MyDemo md2=new MyDemo(5);
md2.display();
MyDemo md3=new MyDemo(5,3);
md3.display();

}
}
 
Output of the code:
$javac MyDemo.java
$java -Xmx128M -Xms16M MyDemo
Value of Value1->0
Value of Value2->0
Value of Value1->5
Value of Value2->0
Value of Value1->5
Value of Value2->3
For first 2 cases , we have called the default constructor and no value has been provided. In that case compiler has put the default values for the numeric datatypes that is 0,0
for the next 2 cases value1 is initiated and value2 is still not initialized hence compiler has put 0.
for the last 2 cases both the values are initialized hence we get what we passed in the argument list.

Constructor Chaining:(Calling constructor from Constructor)
This is useful when some other class extends to base class using extend keyword. In order to reduce the extra code, we can use super keyword to call base class's constructor.
Let us take the earlier example:

public class MyDemo
{
int value1;
int value2;
MyDemo()
{
value1=1;
value2=1;
//some default values instead of zero(0).
}
//below are the argumented constructors
MyDemo(int a)
{
value1=a;
}
MyDemo(int a,int b)
{
value1=a;
value2=b;
}
public void display(){
System.out.println("Value of Value1->"+value1);
System.out.println("Value of Value2->"+value2);
}
public static void main(String args[])
{
DemoChild dc=new DemoChild();
dc.display();

}
}
class DemoChild extends MyDemo{
int value3;
int value4;
//extra variables
DemoChild()
{
super(5);
value3=3;
value4=4;
}
public void display(){
System.out.println("Value of Value1->"+value1);
System.out.println("Value of Value2->"+value2);
System.out.println("Value of Value3->"+value3);
System.out.println("Value of Value4->"+value4);
}
}
 
The output of the code:
$javac MyDemo.java
$java -Xmx128M -Xms16M MyDemo
Value of Value1->5
Value of Value2->0
Value of Value3->3
Value of Value4->4

Constructor Chaining:(using this keyword):

There could be another situation. When we write several constructor for a class,there are times when we would like to call one constructor from another.To avoid duplicating the code,we can do this calling by using a this keyword.
this refers to the current object.In a constructor , the this keyword takes on a different meaning when we pass in an argument list.It makes an explicit call to the constructor that matches the argument list. This makes it straight forward way to call the constructor.

public class Student{
    private String name=new String("null");
    private int roll=0;
    Student(int x)
    {
    roll=x;
    System.out.println("Constructor with int argument "+roll);
    }
    Student(String ss)
    {
        name=ss;
        System.out.println("Constructor with String argument "+name);
    }
    Student(int i,String s){
    //roll=i;
    //we can do this but another approach is
    this(i);
    //but we can not use this for another one
    name=s;
    //but we can do the below
    //this.name=s;
    System.out.println("Constructor with int and String argument "+roll+" "+name);
    }
    
    Student()
    {
        this(10,"Sunil");
        //default constructor
    }
    void print()
    {
        //this(11);
        //not included in constructor hence we can not do this
        // Student.java:32: error: call to this must be first statement in constructor
        //this(11);
        //   ^
//1 error
        System.out.println("Constructor with int and String argument "+roll+" "+name);
    }
    public static void main(String args[])
    {
        Student st=new Student();
        st.print();
    }
}
 
The output of the code:
$javac Student.java
$java -Xmx128M -Xms16M Student
Constructor with int argument 10
Constructor with int and String argument 10 Sunil
Constructor with int and String argument 10 Sunil
we can see another chaining in place.

3 observations:

  1. The Student(int i,String s) shows that while we can call one constructor using this keyword,we can not call two!!.The constructor call should be the first thing do inside another constructor,otherwise we will get error.
  2. In case instance variable and parameter variable same then we need to use this.insatance_ variable=parameter variable, so that compiler don't get confused.
  3. In print method,this(11) gives an error during compilation.It means the compiler will not allow us to call a constructor from inside any other method which is not constructor.


Rules for Constructor Chaining
  1. If super is not called then it will call the default constructor of the parent class.
  2. If super is called with parameter, then overridden constructor will be called to initialize the values. All other values will be set as zero(0).
  3. If super is used, it should be the first line of the constructor of the child constructor in child class.
  4. A constructor of a base class is always called inside constructor of the derived class. This goes in a chained manner until the last base class constructor is called.
  5. A derived class has access only to its own members but not those of base class(whose members are mostly private).Only the corresponding base class constructors have the proper knowledge and access to initialize it's own elements.Thus it is essential that all constructors get called to ensure the object creation is proper and perfect.
Compiler enforces a constructor call for every portion of a derived class. It will silently call the default constructor,if we don't explicitly call a base class constructor in the derived class constructor body.Also if we do not have one default constructor the compiler will place one and continue the constructor chain.Otherwise,if we do not have a default constructor but has an argumented constructor,the compiler will throw an Error.
Constructor Concept Simplified in Java Constructor Concept Simplified in Java Reviewed by Animesh Chatterjee on September 21, 2018 Rating: 5

No comments:

Powered by Blogger.