Java Constructors
Java constructors are special method-like constructs that allow fully initializing the object state before other classes inside the application can use it. Constructors are invoked using new keyword.
1. What is a Constructor in Java?
Constructors are special method-like (but not exactly methods) constructs that help programmers write object initialization code, before the object is available for use by other objects in the application.
Whenever an application needs a new instance of any class, JVM allocates a memory area inside the heap. Then JVM executes the invoked constructor (the class can have multiple constructors) and initializes the object state. Inside the constructor, we can access all object attributes and assign them to their default or desired values.
If we do not define any constructor in a class, JVM automatically inserts a default constructor with an empty body.
2. Default and Parameterized Constructors
The constructors can be of two types. One that accepts no argument is also called the default constructor. Other constructors that accept arguments are called parameterized constructors.
If we do not provide any constructor in the class, JVM provides a default constructor to the class during compile time. In the default constructor, the name of the constructor MUST match the class name, and it should not have any parameters.
Note that we also can override the default constructor and add more code related to state initialization.
2.2. Parameterized Constructor
There can be multiple constructors in a class. We can define overloaded constructors in class that accepts a different set of parameters in each constructor.
public class Employee < private String firstName; private String lastName; public Employee() < //constructor 1 >public Employee(String firstName) < //constructor 2 //statements >public Employee(String firstName, String lastName) < //constructor 3 //statements >>
If we define a non-default parameterized constructor in a class then JVM will not insert the default constructor in the bytecode. In such case, if default constructor is required, we must create the default constructor explicitely.
For example, in the following Employee class, we have created only one parameterized constructor:
If we try to create an instance of Employee using the default constructor, then a compilation error will occur:
Employee employee = new Employee(); //'Employee(java.lang.String)' in 'Employee' cannot be applied to '()'
3. Rules to Create Constructors
There are a few mandatory rules for creating the constructors in java.
- The constructor name MUST be the same as the name of the class.
- There cannot be any return type in the constructor definition.
- There cannot be any return statement in the constructor.
- Constructors can be overloaded by different arguments.
- If you want to use super() i.e. parent class constructor, then it must be the first statement inside the constructor.
4. Constructor Chaining with this() and super()
In Java, it is possible to call other constructors inside a constructor. It is just like method calling but without any reference variable (obviously, as the instance is NOT fully initialized as of now).
Now we can call constructors of either the same class or of the parent class. Both use different syntaxes.
4.1. Calling Same Class’s Constructors with this()
To call other constructors from the same class, use this keyword. In the following code, this() invokes the default constructor, and this(firstName) invokes the first constructor accepting a single argument of type String.
public Employee() < >public Employee(String firstName) < this(); //calling default constructor >public Employee(String firstName, String lastName) < this(firstName); //calling constructor with single argument of String type >
4.2. Calling Parent Class’s Constructors with super()
To call constructors from super or parent class, use super keyword. The usage of super keyword is similar to this keyword – the only difference is that super refers to superclass and this refers to the current instance.
public class Parent < public Parent() < //. >> public class Child extends Parent < public Child() < super(); //invokes Parent's constructor >>
Sometimes we want to protect the constructor from being called by other classes. Altogether we want that nobody should be able to create a new instance of the class.
Why would anybody want that? Well, it’s necessary for singleton pattern. In singleton, an application wants to have one and only one instance of any class.
A common singleton class definition looks like this:
public class DemoSingleton implements Serializable < private static final long serialVersionUID = 1L; private DemoSingleton() < // private constructor >private static class DemoSingletonHolder < public static final DemoSingleton INSTANCE = new DemoSingleton(); >public static DemoSingleton getInstance() < return DemoSingletonHolder.INSTANCE; >protected Object readResolve() < return getInstance(); >>
That’s all about constructors in java. Drop me your questions in the comments section.
Default Constructor in Java – Class Constructor Example
Ihechikara Vincent Abba
In this article, we will talk about constructors, how to create our own constructors, and what default constructors are in Java.
What is a constructor?
As a class-based object-oriented programming term, a constructor is a unique method used to initialize a newly created object (class). There are a few rules you must follow when creating constructors. These rules include:
- The name of the constructor must be the same as the class name.
- The constructor must have no return type.
Before we proceed, let’s see what a class looks like in Java:
The code above shows a class called Student with three attributes – firstName , lastName , and age . We will assume that the class is supposed to be a sample for registering students. Recall that the three attributes do not have any values so none of the information is hard coded.
Now we will use constructors to create a new instance of our Student object. That is:
public class Student < String firstName; String lastName; int age; //Student constructor public Student()< firstName = "Ihechikara"; lastName = "Abba"; age = 100; >public static void main(String args[]) < Student myStudent = new Student(); System.out.println(myStudent.age); // 100 >>
We have created a constructor which we used to initialize the attributes defined in the Student object. The code above is an example of a no-argument constructor. Let’s see an example of a different kind now:
public class Student < String firstName; String lastName; int age; //constructor public Student(String firstName, String lastName, int age)< this.firstName = firstName; this.lastName = lastName; this.age = age; >public static void main(String args[]) < Student myStudent = new Student("Ihechikara", "Abba", 100); System.out.println(myStudent.age); >>
Now we have created a parameterized constructor. A parameterized constructor is a constructor created with arguments/parameters. Let’s break it down.
public Student(String firstName, String lastName, int age)
We created a new constructor that takes in three arguments – two strings and an integer.
this.firstName = firstName; this.lastName = lastName; this.age = age;
We then linked these arguments to the attributes we defined when we created our class. Now we have initialized the Student object using a constructor.
public static void main(String args[])
Lastly, we created a new instance of the Student object and passed in our arguments. We were able to pass in these arguments because we had already defined them in a constructor.
I created one constructor with three arguments, but you can also create separate constructors for initializing each attribute.
Now that you know what a constructor is in Java and how to use it, let’s now look into default constructors.
What is a default constructor?
A default constructor is a constructor created by the compiler if we do not define any constructor(s) for a class. Here is an example:
Can you spot the difference between this and the two previous examples? Notice that we did not define any constructor before creating myStudent to initialize the attributes created in the class.
This will not throw an error our way. Rather, the compiler will create an empty constructor but you will not see this constructor anywhere in the code – this happens under the hood.
This is what the code above will look like when the compiler starts doing its job:
public class Student < String firstName; String lastName; int age; /* empty constructor created by compiler. This constructor will not be seen in your code */ Student() < >public static void main(String args[]) < Student myStudent = new Student(); myStudent.firstName = "Ihechikara"; myStudent.lastName = "Abba"; myStudent.age = 100; System.out.println(myStudent.age); //100 System.out.println(myStudent.firstName); //Ihechikara >>
A lot of people mix up the default constructor for the no-argument constructor, but they are not the same in Java. Any constructor created by the programmer is not considered a default constructor in Java.
Conclusion
In this article, we learned what constructors are and how we can create and use them to initialize our objects.
We also talked about default constructors and what makes them different from no-argument constructors.
Default Constructor in Java
A default constructor in Java is created by the compiler itself when the programmer doesn’t create any constructor. The purpose of the default constructor is to initialize the attributes of the object with their default values.
What is Default Constructor in Java?
A default constructor is created only when we don’t declare any constructor in our code. Then, by default, the compiler automatically creates a default constructor.
Since we know the role of the constructor in Java, the question is, what will happen when there is no constructor available during object creation?
But firstly, we need to look at an important case where we try to access any variable without initialization. Here in this example, we’ll be simply declaring the variables but won’t initialize them with their default values.
Compilation error:
And indeed, this is what you might have expected. The above code has thrown multiple errors. Why? Because we didn’t bother to initialize the variables with their default values. Also, these variables are declared within the static method, so these are static variables. It is important to provide static variables with their default values.
Now, we’ll provide default values for them.
Now, the code is working properly. So, the above example highlighted a common mistake that we, as programmers, might do while creating objects as well.
Instance variables are the ones declared as a property of a class but outside of constructors, methods, or blocks of the class.
So, initializing the instance variables is also mandatory. Here comes the role of a default constructor in Java that assigns these instance variables with their default values.
Note: We usually call the default constructor a no-arg constructor but they are not actually the same. A no-arg constructor is still a constructor created by the user and not by the compiler. Although they both have the same purpose, one is created automatically while the other is created by the user.
Default Constructor Example
Let us take an example of a product that comprises data such as id , product_name , and also price .
Notice what happens when no constructor is declared in the code by a programmer, and still, we are trying to access the instance variables.
It works! The above code didn’t throw any error because the Java compiler provided a default constructor for the code to initialize the attributes with default values. Yes, this default constructor is invisible.
Purpose of a Default Constructor
As discussed above, the purpose of the default constructor is to provide the default values to the object. An integer will be initialized with 0 0 0 , double with 0 . 0 0.0 0 . 0 , boolean with f a l s e false f a l s e , and String with n u l l null n u l l . It depends on the type of instance variable declared in the class from which an object is created.
Let’s consider another case where we’ll create a parameterized constructor.
Compilation error:
We have created a parameterized constructor in our code, and we are trying to access the default constructor. It throws an error .
Note: When we create any constructor manually, then the compiler will not insert the default constructor. So, we’ll also have to create the default constructor manually, if needed.
If we have created a parameterized constructor on our own and by any chance, we tried to call the default constructor, then it is our responsibility to also create our own default constructor as well.
But yes, this only occurs when we call the default constructor, whereas we have created parameterized constructor only. You can see the same in the code given below.
The problem didn’t occur here because we neither created nor called the default constructor. We had a parameterized constructor and we are just calling it, so there isn’t any need for default constructor.
Conclusion
- A default constructor in Java is created automatically by the online Java compiler when the programmer doesn’t create any constructor in the entire program.
- It is created to assign the default values to the instance variables of the class when an object is created.
- Default constructors are sometimes called no-arg constructors since they both work the same. But no-arg constructor is created by the user while default constructor can only be created by the compiler.