Constructor in Java

20:34:00

Constructor is a block of code that allows you to create an object of class. This can also be called creating an instance. Constructor looks like a method but it’s not, for example methods can have any return type or no return type (considered as void) but constructors don’t have any return type not even void.
There are several other differences between them, we will discuss them in detail at the end of this article.
Types of Constructors
There are three types of constructors: 
  1. default, 
  2.  parameterised.

Rules for creating java constructor

There are basically two rules defined for the constructor.
  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type

Advantages of Constructors:



1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
3. While loading the class the object is invoked.


Default constructor: If you do not define any constructor in your class, java generates one for you by default. This constructor is known as default constructor. You would not find it in your source code but it would present there. It would look like this if you could see it. Default constructor for class Demo:
public Demo()
{
}
no-arg constructor: Constructor with no arguments is known as no-arg constructor. The signature is same as default constructor, however body can have any code unlike default constructor where the body does nothing.
Important point to note here is that whatever constructor you write in your class cannot be called default even if you write public Demo() { }in your class it cannot be called default since you are writing it. The constructor is called default only when it has been generated by java.
Example: A no-arg constructor for class Demo
class Demo
{
     public Demo()
     {
         System.out.println("This is a default constructor");
     }
}
Parameterized constructor: Constructor with arguments is known as parameterized constructor.
class Demo
{
      public Demo(int num, String str)
      {
           System.out.println("This is a parameterized constructor");
      }
}
How to call a constructor?
To call a constructor use the keyword new, followed by the name of class, followed by parameters if any. For example to create the object of class Demo, you can call the constructor like this: new Demo()

Object creation using constructor

Lets say class name is “Demo”
1) I’m declaring a reference variable of class Demo-
class Demo;
2) Object creation – Calling default constructor for creating the object of class Demo (new keyword followed by class name)
new Demo();
3) Now, I’m assigning the object to the reference –
class Demo = new Demo();

What if you don’t write a constructor in a class?

As discussed above, if you don’t write a constructor in your class, java would generate one for you. Lets take a look at the code below to understand it litter better:
class Example
{
      public void demoMethod()
      {
              System.out.println("hello");
      }
      public static void main(String args[])
      {
              Example obj = new Example();
              obj.demoMethod();
      }
}
In public static void main I am creating the object of class Exampleand in order to do that I have invoked the default constructor of class Example( note the new Example()). But where did I write the constructor?  No I didn’t the java did it for me.

If you understood the example then I may need to test your skills – Guess the output of below Java program

class Example2
{
      private int var;
      public Example2()
      {
             //code for default one
             var = 10;
      }
      public Example2(int num)
      {
             //code for parameterized one
             var = num;
      }
      public int getValue()
      {
              return var;
      }
      public static void main(String args[])
      {
              Example2 obj2 = new Example2();
              System.out.println("var is: "+obj2.getValue());
      }
}
Output:
var is: 10
Now replace the code of public static void main with the code below and guess answer –
 Example2 obj2 = new Example2(77);
 System.out.println("var is: "+obj2.getValue());
Output:
var is: 77
Explanation: you must be wondering why the answer is 77- Let me explain why is it so – Observe that while creating object I have passed 77 as a parameter inside parenthesis, that’s why instead of default one, parameterized constructor with integer argument got invoked, where in I have assigned the argument value to variable var.
Again, replace the code with the below code and try to find the answer –
 Example2 obj3 = new Example2();
 Example2 obj2 = new Example2(77);
 System.out.println("var is: "+obj3.getValue());
Output:
var is: 10
Important Point to Note: If you are defining parametrised constructor then you may ran into trouble. Handle them with care :)
What kind of trouble? Lets have a look at the code below:
class Example3
{
      private int var;
      public Example3(int num)
      {
             var=num;
      }
      public int getValue()
      {
              return var;
      }
      public static void main(String args[])
      {
              Example3 myobj = new Example3();
              System.out.println("value of var is: "+myobj.getValue());
      }
}
Output: It will throw a compilation error!!. The reason is when you don’t define any constructor in your class, compiler defines default one for you, however when you declare any constructor (in above example I have already defined a parameterized constructor), compiler doesn’t do it for you.
Since I have defined a constructor in above code, compiler didn’t create default one. While creating object I am invoking default one, which doesn’t exist in above code. The code gives an compilation error.
If we remove the parametrised constructor from the code above then the code would run fine because, java would generate the default constructor if it doesn’t find any in the code.

Constructor Chaining

Constructor chaining is nothing but a scenario where in one constructor calls the constructor of its super class implicitly or explicitly. Suppose there is a class which inherits another class, in this case if you create the object of child class then first super class(or parent class) constructor will be invoked and then child class constructor will be invoked.
Have a look at the example below:
class Human
{
        String s1, s2;
        public Human()
        {
              s1 ="Super class";
              s2 ="Parent class";
        }
        public Human(String str)
        {
               s1= str;
               s2= str;
        }
}
class Boy extends Human
{
        public Boy()
        {
              s2 ="Child class";
        }
        public void disp()
        {
               System.out.println("String 1 is: "+s1);
               System.out.println("String 2 is: "+s2);
        }
        public static void main(String args[])
        {
                Boy obj = new Boy();
                obj.disp();
        }
}
Output:
String 1 is: Super class
String 2 is: Child class
Explanation of the example:
Human is a super class of Boy class. In above program I have created an object of Boy class, As per the rule super class constructor (Human()) invoked first which set the s1 & s2 value, later child class constructor(Boy()) gets invoked, which overridden s2 value.
Note: Whenever child class constructor gets invoked it implicitly invokes the constructor of parent class. In simple terms you can say that compiler puts a super(); statement in the child class constructor. Read more about super keyword here.
Question you may have: In the above example no-arg constructor of super class invoked, I want to invoke arg constructor(Parameterized).
Its so simple.
change the code of public Boy() to something like this –
Note: super() should be the first statement in the constructor.
public Boy()
{
     super("calling super one");
     s2 ="Child class";
}

Understood till now – Here are few more points about constructors

1.     Every class has a constructor whether it’s normal one or a abstract class.
2.     As stated above, constructor are not methods and they don’t have any return type.
3.     Constructor name and class name should be the same.
4.     Constructor can use any access specifier, they can be declared as private also. Private constructors are possible in java but there scope is within the class only.
5.     Like constructors method can also have name same as class name, but still they have return type, though which we can identify them that they are methods not constructors.
6.     If you don’t define any constructor within the class, compiler will do it for you and it will create a constructor for you.
7.     this() and super() should be the first statement in the constructor code. If you don’t mention them, compiler does it for you accordingly.
8.     Constructor overloading is possible but overriding is not possible. Which means we can have overloaded constructor in our class but we can’t override a constructor.
9.     Constructors can not be inherited.
10.         If Super class doesn’t have a no-arg(default) constructor then compiler would not define a default one in child class as it does in normal scenario.
11.         Interfaces do not have constructors.
12.         Abstract can have constructors and these will get invoked when a class, which implements interface, gets instantiated. (i.e. object creation of concrete class).
13.         A constructor can also invoke another constructor of the same class – By using this(). If you wanna invoke a arg-constructor then give something like: this(parameter list).




You Might Also Like

0 comments

Popular Posts

Like us on Facebook