Constructor Concept Simplified in Java

0
24
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Constructor in Java
Constructor in Java

Constructor in Java:

Objects are created with new operator and with some method call.This method call is nothing but the constructor. Which is responsible for creating the object properly and 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 ‘’ or null,for reference variables are set to null.

Constructors Vs other methods:

Constructors are not instance methods as they don’t belong to objects. They are only responsible for creating objects.They do exist before any object is created.In this way they are static member function but according to the java language specification, they are not technically a member of the class hence they can not be static.They are not referred to as methods.

How Construct actually works:

The mechanism to call a constructor with a new keyword followed by the class name as constructor name with parameter list. Parameter list can be empty.

new (class name)(parameter list);
MyClass mc=new MyClass();
//or
new MyClass()
 

The constructor returns the reference of the newly created object.Sometimes we can call the constructor without creating a reference variable.It is legal but we can not use that object later as we did not store the object reference in the handle. They are ready to be garbage collected as soon as the execution is over.

The constructor does the following things:

  1. The constructor gets a block of unused memory in the heap.The memory is large enough to hold the specified object of the specified type.
  2. It initialize the instance variables of the object.If the declaration of an instance variable specifies an initial value,then the value is computed and stored in the instance variable. Otherwise the default values are used.
  3. The actual parameters in the constructor , if any are evaluated and the values are assigned to the formal parameters of a constructor.
  4. The statements or the block part of the body of the constructor if any are executed.
  5. A reference to the object is returned as the value of the constructor call.
At the end what we get is a reference to a newly created object.We can use this reference to get at the instance variables in that object or to call its instance methods.

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.
  4. They can not declared as static.
  5. The only modifier that can be used on a constructor definition are the access modifier-public, private and protected.

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.It has the below roles:

  1. allocate memory for the new object.
  2. initialize the variables to default values.

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.Constructors can be overloaded with different parameter lists.  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();

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

LEAVE A REPLY

Please enter your comment!
Please enter your name here