Skip to main content

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

Multithreading in java with example

Multithreading  is one of the most important concept in core java. In this article we will learn what is multithreading? , what is the use of it? and What is the use of Synchronization and when to use it?  with detailed examples. At a time, two or more threads are accessing the same object is called as Multithreading  in Java .  First, we will create two threads for two objects. It is also possible to run two or more threads on a single class object. In this case, there is a possibility to get unreliable results. If the two threads are perform same task, then they need same object to be executed each time. For your better understanding, take an example of any reservations like, railway, movie ticket booking,etc. Let us think only one berth is available in a train and two passengers are asking for that berth. The first person has sent a request to allocate that ticket/berth to him. At the same time, the second person also sent a request to allocate that ...

JNDI configuration for Tomcat 9 with Oracle

In this article, I am going to place the required source code to get data from the table by using the JNDI configuration. Below are the environment details that I have configured currently. Windows - 7 Oracle - 10g Tomcat - 9 JDK - 8 Eclipse Oxygen Ojdbc6 jar required First, we need to create the Dynamic Web Project. If you don't know how to do <Click Here>. I have faced a lot of issues before getting the output like 405, No driver class to load, etc. I am using JSP & Servlets in the current explanation. Before started writing the application logic, we need to do the below configuration in the installed tomcat directory. Place OJDBC6.jar in the Tomcat LIB directory. Add this Resource under <GlobalNamingResources> in Server.xml file which is present under the conf directory in Tomcat. < Resource name = "jdbc/myoracle" global= "jdbc/myoracle" auth = "Container" type= "javax.sql.DataSource" driverClass...

Git installation for AngularJS 2 in Windows 10

Download Git latest version from https://git-scm.com/downloads or you click on the below link to download directly for windows https://git-scm.com/download/win . Once download completes, click on executable file to start installation process and choose Yes to allow the software installation in windows 10. Click on Next button to continue further installation. Browse the isntallation directory and click on Next button to continue. Select the list of components which you want to be installed and click on Next button to proced further installation. Type the shortcut name for Start menu and click on Next button. Select how you want to use the Git and click on Next button. For Windows no need to change anything, let it be the default one. Choose the Use the OpenSSL library and click on Next button. Select how should Git treat line ending in text files and click on Next button. Select which terminal emulator to use with Git and click on Next button. Configure extr...