Introduction to Java class constructor
A Java class constructor is a special method that is called when an object is instantiated. In other words, when we use the new keyword. The purpose of a Java class constructor is to initialize the newly created object before it is used. A Java class constructor initializes instances (objects) of that class. In this tutorial, we will learn more about java class constructors.
We will cover the default java constructor and parameterized constructor by taking various examples of each. At the same time, we will also discuss constructor chaining and overloading using by solving different examples. In a nutshell, this tutorial is going to be one of the informative tutorials which contain all the necessary information and examples about java class constructors.
Getting started with Java class constructor
As we already discussed in the beginning that java constructors are used to initializing the object’s state. It is like a method that also contains a collection of statements or instructions that are executed at the time of Object creation.
A constructor is called when each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class. So, we can say that a constructor is invoked at the time of object or instance creation. In this section, we will see the simple syntax of the java constructor and will differentiate between the java constructor and the java method.
Difference between Java class constructor and Java method
People mostly mix java class constructors with java methods. In reality, they are different terms performing different operations. The following list highlights some of the differences between a java constructor and a method.
See the list below:
- A constructor is a block of code that instantiates a newly created object, while a method is a set of statements that always return value depending upon its execution.
- The name of the java constructor is always the same as the main class. On the other hand, the name of the method can be anything, not necessary to be similar to the name of the class.
- Constructors are called implicitly, while we call the methods explicitly.
- A constructor does not have any return type, not even void, but methods must have a return type.
- The compiler automatically creates the constructor if there is no constructor in the class. But, in the case of the method, there is no default method provided by the compiler.
- We can override a method but we can’t override a constructor.
Java default constructor
A Default Constructor is a constructor with no parameter which the Java compiler automatically creates if we do not write any constructor in our program. This default constructor is not explicitly mentioned in our source code or the java file as the compiler automatically puts it into the Java code during the compilation process and therefore we will not find it in our java file, rather it exists in the bytecode or .class file.
In this section, we will cover the simple syntax of the default java constructor and will solve an example as well.
Syntax of Java default constructor
As we already discussed that if we will not define any constructor in our Java class, the compiler will create a default one. The syntax of the Java default constructor is very much simple. See the following syntax of the java default constructor.
// java main method
public class Main {
// java default constructor syntax
public Main(){
}
}
Notice that the Java class name and the constructor names, are the same and the default constructor does not take any kind of arguments.
Example of Java default constructor
Now we have sufficient knowledge about the default constructor and we already know its syntax. One more thing that we need to know about the java default constructor is that if we do not provide a user-defined constructor in a class, the compiler initializes member variables to their default values such as:
- numeric data types will be set to 0.
- char data types set will be set to the null character (‘\0’).
- reference variables will be set to null.
Let us now take an example and see how it is used in our Java main class. See the example below:
// creating class named Person
class Person{
// creating instance variables
int number;
String name;
Person(){
System.out.println("This is default constructor!!!");
}
}
// java main class
public class Main{
// Java main method
public static void main(String[] args){
// Creating new object of type person
Person object = new Person();
// Printing the default values of the instance variables
System.out.println(object.name);
System.out.println(object.number);
}
}
Output:
This is default constructor!!!
null
0
Notice that when we create the object, the default constructor was run. And we get values null and 0 because as we already discussed that the default value for the string is null and for integer is 0.
Java parameterized constructor
A constructor is called parameterized constructor when it accepts a specific number of parameters to initialize data members of a class with distinct values. We can use parameterized constructors mainly to initialize the members of the class with different values or objects. In this section, we will see the basic syntax of parameterized constructor and will take an example as well.
Syntax of Java parameterized constructor
A Parameterized constructor is a constructor with a specific number of parameters. We can use parameterized constructors mainly to initialize the members of the class with different values or objects. Here is a simple syntax of java parameterized constructor:
See the example below:
class Main{
DataType1 variableName1;
DataType2 variableName2;
.
.
DataTypen variableNamen;
Main(DataType1 variableName1, DataType2 variableName2, .. , DataTypen variableNamen){
this.variableName1 = variableName1;
this.variableName2 = variableName2;
.
.
this.variableNamen = variableNamen;
}
}
Notice that we defined few variables just below the Main class and we take different arguments( it can be any number of arguments) in our constructor. Then inside the constructor we defined the instance variables to be equal to the provided arguments.
Example of Java parameterized constructor
Now we know how the parameterized constructor works. Let us know take an example and see how actually we can pass arguments to the parameterized constructor. See the example below:
// person class
class Person{
// instance variables
String name;
int age;
//Creating a parameterized java constructor
Person(String name, int id){
this.name = name;
this.age = id;
}
}
// java main class
public class Main{
// java main method
public static void main (String[] args){
// creating new object of type person
// providing the arguments as well
Person object = new Person("Bashir", 22);
// printing
System.out.println("Name: " + object.name );
System.out.println("Age: " + object.age);
}
}
Output:
Name: Bashir
Age: 22
Notice that the two arguments were passed to the constructor, which were then used to define the instance variables of the class.
Java constructor chaining
Java constructor chaining is a process in which a constructor calls another constructor of the same class with the current or present object. The concept of constructor chaining helps to pass the parameters through different constructors, but with the same object. See the diagram below which explains the chaining of constructors in java.
In the above diagram, when we create an object without passing the arguments, then the very first constructor will be executed, which will call the second one because we are passing an argument there. In a similar way, it will call another one and so on. Now, let us take an example and see how it actually works. See the following example.
// java person class
class Person{
// instance variables
String name;
int age;
// java class constructor without any arguments
Person(){
// calling another constructor
this("Bashir");
}
//java class constructor with one argument
Person(String name){
// calling another constructor
this("Bashir", 22);
}
//java class constructor with two arguments
Person(String name, int id){
this.name = name;
this.age = id;
}
}
// java main class
public class Main{
// java main method
public static void main (String[] args){
// creating new object of type person
// providing the arguments as well
Person object = new Person();
// printing
System.out.println("Name: " + object.name );
System.out.println("Age: " + object.age);
}
}
Output:
Name: Bashir
Age: 22
Notice that while creating a new object type of Person, we didn't pass the arguments. They were passed while executing the chain of constructors.
Overloading Java constructor
Java Constructor overloading is a technique in which a class can have any number of constructors that differ in the parameter lists. The compiler differentiates these constructors by taking into account the number of parameters in the list and their type. Usually, they are arranged in a way that each constructor performs a different task. In this section, we will take the example of a java overloading constructor so that you will know how it actually works.
Example of overloading Java constructor
Now let us take a practical example to see how the overloading of constructors works in java. See the example below:
// java person class
class Person{
// instance variables
String name;
int age;
//java class constructor without any arguments
Person(){
// printing
System.out.println("Constructor without any arguments");
}
//java class constructor with one argument
Person(String name){
System.out.println("Constructor with one argument");
}
//java class constructor with two arguments
Person(String name, int id){
System.out.println("Constructor with two arguments");
}
}
// java main class
public class Main{
// java main method
public static void main (String[] args){
// creating new object of type person
// providing the arguments as well
Person object1 = new Person();
Person object2 = new Person("Name");
Person object3 = new Person("Name", 22);
}
}
Output:
Constructor without any arguments
Constructor with one argument
Constructor with two arguments
Notice that each of the constructors was run by the compiler based on the number of arguments that were passed to the object.
Summary
A Java constructor is a special method that is called when an object is instantiated by using a new keyword. The purpose of a Java constructor is to initialize the newly created object before it is used. Whenever an object is created, the constructor will be executed. In this tutorial, we learned about Java class constructors. We covered two different types of constructors including default and parameterized constructors by taking various examples. Moreover, we also discussed the constructor chaining and overloading of java constructors.
To summarize, this tutorial contains all the information and examples that you need to know in order to get started with java class constructor.
Further Reading
Java class constructor
Constructors in java
Java methods