Constructors in java

Constructors will play key roll in any language while creating an object of a class. In Java, Constructors are useful for create an object of a class. Constructor is also a special method which contains the same name as the class. Constructors differ from other methods in that:
            • Constructors never have an explicit return type.
            • Constructors cannot be directly invoked
            •  Constructors cannot be synchronized, final, abstract, native or static.

Types of constructors in Java:
        There are mainly two types of constructors in Java, one is default constructor and parametric constructor.


Default Constructor: Default Constructor is a constructor which does not contains any of the parameters. If we are not using any of the parametric constructor it is not required to declare default constructor, because JVM automatically will creates.
Here is the signature how to define a default constructor in java.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package com.javatbrains.constructor;

public class A {
     // default constructor declaration
     public A() {
          // This will be invoked at the time of initializing class A
     }
    
     public static void main(String[] args){
          A a = new A();
     }
}

          In the above example I have declared a default constructor for class A. That will be invoked at the time of creating an object for class A. If you are not using any of the parametric constructor, there is no need to define default constructor in a class. Because, JVM will internally creates the default constructor at the time of the object creation.
Parametric Constructor:
          If you have defined any of the constructors with one or more parameters, that constructors are called as parametric constructors in java.
          If you have defined any of the parametric constructor in a class, better you must define a default constructor also.
For example, we have class called A and we have defined a constructor with single parameter and we have not defined any of the default constructor in our class. When we will try to crate and object for our class without passing any values, it will be not possible. Because we have not defined the default constructor here. See the below example,  

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package com.javatbrains.constructor;

public class A {
     // parameter constructor declaration
     public A(int a) {
     // This will be invoked at the time of initializing class A with matching parameters
     }
    
     public static void main(String[] args){
          A a = new A();
     }
}
          The above class shows you a compilation error. Because, you have not defined any of the default constructor and you are trying to create an object by using default constructor. For removing the compilation problem you must define a default constructor or must use the matching parametric constructor. For example,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
package com.javatbrains.constructor;

public class A {
     // parametric constructor declaration
     public A(int a) {
     // This will be invoked at the time of initializing class A with matching parameters
     }
    
     public static void main(String[] args){
          A a = new A(10);
     }
}
          The above program will resolves the problem of compilation error. While creating the object of class A we are passing matching integer type of value. So, It will not show any compilation problems.

Constructor Overloading:
          If you have defined default and parametric constructors in a class that is called the constructor overloading. In java, which of the two or more constructors will have same name and different signature is called the constructor overloading. For example, see the below program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package com.javatbrains.constructor;

public class A {
     // default constructor declaration
     public A(){}
    
     //Parametric constructor declaration
     public A(int a,String b) {
          // This will be invoked at the time of initializing class A
     }
    
     public static void main(String[] args){
          A a = new A(10,"JavaTBrains");
     }
}
          In the above example we have declared two constructors one is without parameters and one more is with parameters. But, there constructors name will be same.

Singleton class:
          Singleton means we will create only one instance of the class and we will use same instance n number of times where it is required in application.

          Constructor can use any access modifier even private also. If a constructor is declared as private in a class then it will creates only one object to its class, that type of classes are called as Singleton classes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package com.javatbrains.constructor;

class Singleton {
     private static Singleton single = null;

     private Singleton() {
          System.out.println("Inside Constructor");
     }

     public static Singleton stFactory() {
          if (single == null) {
              single = new Singleton();
          }
          return single;
     }

}

          In any of the other classes you can access Singleton class and try to call stFactory() more than 1 time. But, It will instantiate at first time of the Singleton class is calling and remaining times it will return existing instance to all.

          Here are the differences between constructor and methods in java.

Constructor
Method
1. Constructor creates and initialises the objects.
1. Methods perform operations on objects.
2. Constructors doesn't exists yet
2. Methods will exists after done operation completed also.
3. Constructor can not be called directly, they are called implicitly when new operator creates and object.
3. Method can be called directly on an object, that has been already created with new.
4. Constructors never have an explicit return type
Methods should have a return type
5. Constructors cannot be synchronized, final, abstract, native or static
5. Methods can be synchronized, final, abstract, native or static
6. Constructor name and class name should be same.
5. Method names and class names  are same or different also

Interview Questions ans Answers:

Q1: What is the use of 'super' keyword inside a constructor?

A: The 'super' keyword is used to invoke the constructor of the parent class. This is invoked by the default when the constructor of any class is called, i.e. a call to the default constructor of parent class is inserted at the beginning of the constructor of child class and it gets executed first and then the execution continues with the child class constructor.

Q2: Can a constructor be private?

A: Yes, it can be private. We use this feature in Singleton pattern to prevent anyone from instantiating the class directly. Instead an instance can be got by invoking a static method on the class.

Q3: How to this() and super() method used with constructors?

A: this() method within a constructor is used to invoke another constructor in the same class. Super() method within a constructor is used to invoke its immediate super class constructor.

Q4: What is the difference between default constructor and parametric constructor?

A:
Default Constructor
Parametric Constructor
1. Default Constructor is useful to initialize all objects with same data
1. Parametric Constructors is useful to initialize each object with different data
2. Default Constructors does not have any value
2. Parametric Constructors will have 1 or more parameters
3. When data is not parsed at the time of object creation default constructors called
3. When data is parsed at the time of object creation parametric constructor is called

Q5: What is a constructor called, before or after creating the object?

A: A constructor is called concurrently when the object creation is going on. JVM first allocates the memory for the object and then executes the constructor to initialize the instance variables. By the time, object creation is completed, the constructor execution is also completed.

Q6:
What is the difference between constructor and method?

A:
Constructor
Method
1. Constructor creates and initialize the objects.
1. Methods perform operations on objects.
2. Constrictors doesn't exists yet
2. Methods will exists after done operation completed also.
3. Constructor can not be called directly, they are called implicitly when new operator creates and object.
3. Method can be called directly on an object, that has been already created with new.
4. Constructors never have an explicit return type
Methods should have a return type
5. Constructors cannot be synchronized, final, abstract, native or static
5. Methods can be synchronized, final, abstract, native or static
6. Constructor name and class name should be same.
5. Method names and class names  are same or different also

Q7:
What is Constructor overloading?

A: Writing two or more constructors with the same name with different parameters is called constructor overloading.

Comments

Popular posts from this blog

how to count the page views by using JSP

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Multithreading in java with example