JavaAn Introduction to Using Constructors in Java

An Introduction to Using Constructors in Java

Java Developer Tutorials

A constructor is a special Java method that is used to initialize some data whenever you instantiate a class. This method is automatically called when you create an object.

By default, all Java objects have a no-arg constructor. That is, a constructor that takes in no arguments.

Programmers can also define their own constructor. In this Java programming tutorial, you will learn how to create and define constructors.

Read: The Top Tools for Remote Developers

How to Create a Constructor in Java

A constructor is similar to normal Java methods; however, a constructor does not have any return type. To create a constructor, simply use the same name as that of your class, as shown in the code example below:

class Fruits {
// this method below is the constructor 
Fruits (){
// some code here
}
}

Within the curly brackets { }of a constructor, you can define the parameters that it will take. These parameters can be primitive data types (such as int or float), or they can even be reference types (such as arrays or Objects).

How to Use Constructors in Java

Once you instantiate a class, the code in your constructor automatically runs. This is specifically true if you have defined a no-arg constructor. In the event your constructor has a parameter list, then you will need to provide the necessary arguments when instantiating the class, as is the case in the follow Java code example:

MyClass instance1 = new MyClass(arg1, arg2);

The passed arguments will be used to initialize the constructor for the created object. See the sample code below. It demonstrates the concepts that have just been discussed:

class MyConstructor {
   public MyConstructor(int x, String s1){
       int height = x;
       String name = s1;
   }
 
   public static void main(String args[]) {
       MyConstructor mycont = new MyConstructor(8, "Jay");
   }
}

Just like with methods, the accessibility of constructors can be restricted using visibility modifiers, including: public, private, protected. For example, if you tried to access a constructor with private visibility in a subclass, you would get a compilation error.

Read: Tips to Improve Performance in Java

Using the Java Keyword: this

It is possible that your constructor’s parameter list may have variable names similar to the ones of your class’ instance variables. Java allows shadowing of the class variables inside your constructor, so that you can be able to use the same variable names.

Developers can access the shadowed variables (or any member of the class) using the Java keyword this. The keyword this is used to refer to the current object.

See the example below, demonstrating how to use the this keyword in Java:

class MyConstructor {
   int x = 0;
   String s1;
 
   private MyConstructor(int x, String s1){
       x = this.x;
       s1 = this.s1;
   }
 
   public static void main(String args[]) {
       MyConstructor mycont = new MyConstructor(5, "Jack");
   }
}
 

What is Constructor Chaining in Java?

Note that the keyword this is not just for accessing instance members. It can also be used to call constructors inside other constructors. This is known as constructor chaining.

Programmers can have as many constructors in their classes as they want, so long as they have differing method signatures. When the this keyword is used to call another constructor inside the current constructor, it must be the first expression in the calling constructor. It is important to note that at least one of the chained constructors should not be using the this keyword. See the code example below showing how to chain constructors in Java:

public class ConstructorUsingThis{
   ConstructorUsingThis(){
       System.out.println("\nThis msg is from the no-arg constructor.");
   }
 
   ConstructorUsingThis(int y){
       this();
       int num = y;
       System.out.println("This msg is from the constructor with one argument: " + num);
   }
 
   public static void main(String[] args){
       ConstructorUsingThis Obj = new ConstructorUsingThis(85);
   }
}

Final Thoughts on Constructors in Java

By now, you should be comfortable creating constructors on your own. As mentioned earlier, constructors are used to initialize values at object creation. A good example of values that are usually initialized are database entries.

Read more Java programming tutorials and software development guides.

Latest Posts

Related Stories