A constructor is like a special method in a Java class; its name is the same as the class name, and it does not return any value after execution.
A Constructor is called at the time of object initialization. The JVM first allocates memory for the object and then executes the constructor to initialize the instance variables. Once object creation is completed, constructor execution is also completed.
In Java, Every class must have a constructor. If we don't define a constructor in a class, then the compiler automatically creates a default constructor (with no arguments) for the class.
We declare constructors with access modifiers as public, protected, private, or none.
Constructors be abstract, final, native, static, or synchronized.
Types of Constructors in Java
There are two types of constructors in Java:
No-argument Constructor (Default Constructor)
Parameterized Constructor
In Java class, we can have only one No-argument constructor (default constructor) and many Parameterized constructors with different parameters. It is not mandatory to explicitly create a constructor in a class; if there is no constructor, the Java compiler creates the default constructor.
Now, Let's get into the details about the constructor's types and their implementation in a Java class.
No-argument Constructor
A constructor that has no parameter is known as the No-argument or default constructor in Java. If we don’t define a constructor in a class, then the compiler creates a default constructor (with no arguments) for the class. A class can have only one No-argument Constructor.
Example 1 : A Java Program of default constructor
Output
Employee class default constructor...
Parameterized Constructor
A constructor that has parameters is known as a parameterized constructor in Java. A parameterized constructor must have at least one parameter. If we want to initialize fields of the class with different values to distinct objects, then use a parameterized constructor. We can declare any number of parameterized constructors in our class.
Example 2 : A Java Program of parameterized constructors
Output
First Parameterized Constructor execution started... Employee Name : Shreyansh
Second Parameterized Constructor execution started... Employee ID : 101 Employee Name : Shreyansh
Third Parameterized Constructor execution started... Employee ID : 101 Employee Name : Shreyansh Employee Basic in LPA : 30.75
Private Constructor in Java
Java allows us to declare a constructor as private. A private constructor is used to restrict object creation outside the class, which means once the constructor is declared as private, we cannot create the object outside the class.
See the declaration of the private constructor:
private constructorName() {
// Code
}
In the Singleton Design Pattern, we declare the constructor as private.
Let's see how to implement a private constructor in a Java program.
Example 3 : A Java Program of private constructor
Output
Private Constructor is called...
myMthod called...
If we try to create object outside the class then see what will happen.
Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor PrivateConstructorExample() is not visible
at com.javabytechie.constructor.OutsiderClass.main(PrivateConstructorExample.java:3)
Difference between Constructor and Method
A constructor is similar to a method, but it is not the same as a method. Let's see the differences between both in the below table.
Constructor
Method
1.
Constructor name must be the same as the class name.
Method name may be any valid name.
2.
Constructor is responsible for object initialization.
Method is used to perform any kind of specific job.
3.
Constructor is invoked implicitly only at the time of object creation.
Method can be called many times or any time after object creation.
4.
Constructor does not return any value.
Method may or may not return any value.
5.
If a constructor is not declared in the class, a default constructor is provided by the Java compiler.
Whereas In methods, no default method is provided by the Java Compiler.
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
Please share this article on social media to help others.
If you have any query or suggestion regarding this artical please share with us feedback@javabytechie.com
Constructor - Interview Questions and Answers
What happens, when a Constructor is called in Java?
Ans. In Java, whenever we are creating a new object, at least one constructor is invoked to initialize the data members of the class.
Employee emp = new Employee();
Here, Employee Object is being created using the 'new' keyword. At the time of execution of this line, the Java compiler first allocates memory for the 'emp' object in heap memory and then checks whether this class has any constructor or not if there is no constructor written by the developer the Java compiler creates a default constructor and start object initialization in the heap memory area.
During Object initialization, the constructor provides the default values to the object like 0, null, etc. depending on the type if there is no default value provided by the developer. But in this case, if the value is assigned, then the constructor initializes with the given value.
Can we declare Constructor as static in Java?
No, because the static keyword belongs to a class rather than the object of a class, a static property is always accessed with its class name. In Java, a constructor is called when an object of a class is created, so there is no sense to declare a constructor as static.
Can we declare Constructor as final in Java?
No, Java does not allow the declaration of a constructor as final. We will get a compile-time error if try to do so.
Can we declare Constructor as abstract in Java?
No, the abstract will only use with class and method. abstract cannot be used with constructors, variables, or blocks in Java.
Does Java allow calling a sub-class constructor from a super-class constructor?
No, Java does not allow it.
Can we write a method name same as the class name?
Yes, It is possbile to write a methed name same as the class, this method will be called by the object the class same as normal method call but it is not recommended as per coding standards.
How does the Java default constructor be provided?
If a Java class does not have any constructor, the compiler will automatically provide one default constructor. A default constructor does not contain any parameter. The access modifier of the default constructor is the same as the class itself.
Can we use both 'this' and 'super' in the same constructor?
No, because both 'this' and 'super' should be the first statement in the constructor.
What are the Rules for defining a constructor in Java?
Ans. Always remember the following points while writting a constructor in Java:
✅ The constructor name must be the same as the class name.
✅ It cannot contain any return value.
✅ It can be declared as private, public, protected, default (Access Modifiers).
✅ It cannot be final, static, abstract, synchronized (Non Access Modifiers).
✅ It can be declared parameterazed or non-parameterazed.
✅ It can throw an exception, so it can have a throws clause.
Can we have a Constructor in an Interface?
No, Java does not allow to define a constructor inside an Interface.
Can we have a Constructor in an abstract class?
Yes, an abstract class can have a constructor same as a normal class in Java.
Why constructors cannot be abstract in Java?
When we declared a method as abstract that means that method doesn't have a body and it should be implemented in a child class only. But the constructor is called implicitly when the new keyword is used so it can't lack a body.
Can we declare try-catch blocks inside a constructor?
Ans. Yes, Java allows declaring try-catch blocks inside a constructor. Let's see the example below.
class Test {
Test(){
String str = null;
try {
System.out.println("Length: " + str.length());
}
catch (NullPointerException e) {
System.out.println("String object cannot be null");
}
}
}
public class ConstructorWithTryCatch {
public static void main(String[] args) {
Test obj = new Test();
}
}
Output
String object cannot be null
What is the use of declaring a constructor as protected?
In Java, a protected method can be accessed by any class from a different package by using inheritance only. But, when we declare a constructor protected, it behaves slightly differently than a method. The protected constructor can only be accessed by using a super keyword according to Java language standards.
What is order of calling constructors in inheritance?
Ans. In inheritance, constructors are called from the base class to derived class that means first base class constructors will be called then derived class constructors. For example,
class A {
A() {
System.out.println("A class constructor called.");
}
}
class B extends A {
B() {
System.out.println("B class constructor called.");
}
}
class C extends B {
C() {
System.out.println("C class constructor called.");
}
}
public class ConstructorsCallinginInheritance {
public static void main(String[] args) {
C obj = new C();
}
}
Output
A class constructor called. B class constructor called. C class constructor called.