Podcast1Let's get this episode started with a quick explanation on what a constructor is…

When you instantiate an Object in Java, the first thing it will do is execute the code inside the Object's constructor. Simple as that! Each Object can have their own constructor (even multiple constructors if need be), and their purpose is to sort of “initialize” the Object for use in your application.

This is loosely similar to the public static void main method, in that when Java starts up, it searches for this method and runs the code. So when you instantiate an Object, Java will look to the constructor to start the process.

You may ask yourself, “Well if constructors are what Java turns to when I instantiate a new Object, why am I only hearing about this now?”. Well, constructors are not mandatory to use, you can get away without having one in your code. All Java will do if it doesn't detect a constructor is look up in the Object's hierarchy to see if any of the super classes have defined a constructor. If it doesn't find any, then it will essentially just do nothing to initialize the Object (no hard feelings).

Alright, so if you've never used a constructor before, you're probably wondering what the advantages are to using one. Well, in my experience constructors are mostly used to give a particular Object a “default state”.

An example that I like to use is if you were to have a HumanBeing Object. A HumanBeing has properties like: name, age and gender. So let's say that anytime we initialize a new HumanBeing Object, we would like to set some default values to all these properties. It's sometimes a good idea to set default values to properties to avoid NullPointerExceptions (or other strange behaviours in your application). In the case of the HumanBeing class, we could set the default name to be “John Doe”, the age could be arbitrarily set to 25 and the gender could be set to male.

So what does this mean? Well it means that if you were to instantiate a HumanBeing object via the new HumanBeing() code, then your newly created HumanBeing will be a 25 year old male named John Doe. Fair enough, but what if you know the name, age and gender you want to set, what then? Great question…

In Java, you're allowed to use many constructors if you so choose. Each constructor just has to have a different signature. This means that every constructor needs to have a different set of parameters being passed into it.

So in the case that you know all the properties you wish to set, then you could create a constructor that takes three parameters: name, age and gender. This way, when you initialize your HumanBeing Object, you can pass in all the necessary data.

Alright, so you're now familiar with the concept of a constructor, you know they're used to initialize an Object (namely to set up the properties of the Object). You are aware that you can have more than one constructor if need be, but what does the code look like?

Well, believe it or not, if you already know how to create a method in Java, then I'm sure you can figure out how to create a constructor as well. The code for a constructor just consists of three parts: the access modifier, the name and the parameters.

The access modifier is just the public, private or protected keyword that you've seen many times. In the majority of the cases, your constructor will likely have a public modifier, because you usually want any Class to be able to instantiate your Object. There is one scenario when you wouldn't want a public constructor, and that's when you want to make your Object a Singleton, but that's a slightly more advanced topic that I will be covering later in the podcast. Alright, so, you'll most likely be using the public modifier, so what's next?

The name of the constructor… and this one is kind of a no-brainer. The name of your constructors has to match the name of the Object, period. So since I've said that our example Object is the HumanBeing Object, then our constructors names will be just that. public HumanBeing… remember that it's case sensitive, so match the upper case and lower case of your Class name.

The final piece is the parameters. You can create a constructor with no parameters, this is normally referred to as a no-argument constructor. This is the type of constructor we would use when we have no indication of how this Object should be initialized, and therefore we would pick default values for the Object ourselves. For our example we chose John Doe, the 25 year old male. No-argument constructors are certainly useful and there's no reason not to use them, so don't be shy! If, on the other hand, you know you want to give your Object a certain set of data, then you would create another constructor (using the same rules that we just talked about) only this time, you would specify what parameters it should take.

So to put it all together, our constructor would be:

  public HumanBeing(String name, int age, String gender)
  {
    // 3 argument constructor for the HumanBeing Class
  }

So just keep in mind that the same rules for method signatures apply for constructors. You can't have two constructors that take the same parameters. In our example we have a no-argument constructor, so there can only be one of those in your HumanBeing class and we have a 3 argument constructor that takes a String, int and String… so we cannot have another constructor that also takes a String, int and String (as that would be a duplicate method signature).

One last piece of advice, is that sometimes you may want to execute a constructor from within another constructor. In order to do this, you just use the this keyword followed by the parameters. Here's an example:

public class HumanBeing
{
  private String name;
  private int age;
  private String gender;

  public HumanBeing()
  {
    this("John Doe", 25, "male");
  }

  public HumanBeing(String name, int age, String gender)
  {
    this.name = name;
    this.age = age;
    this.gender = gender;
  }
}

There you have it: The Java constructor!

Free Java Beginners Course

Start learning how to code today with our free beginners course. Learn more.