Friday, September 2, 2016

JAVA 13 - Constructors and overloading

Last time we started to look at classes in Java and created an initial dice class, which included the following declaration to create a class instance (or object) ...

ClassName  objName = new ClassName();

Here the ClassName() is actually calling a method called the constructor.  Every method has a default constructor, they set up the attributes, although they don't initialise them (that is set to an initial value).

In our previous Java class, we created a dice object, then set up the number of sides on the dice.  Really that's the kind of thing we want to do when we create an object, so it makes sense to define a new constructor to do this.

But first ... packages

Before I go to look at this, it's worth covering off packages.  You can define a package in Eclipse under your project with a right click ...

A package creates a common work area (a bit like a personalise library) - any classes you have under the same package have visibility of public methods and attributes of other classes which are under this area and start with ...

package packageName;

For this piece, we're going to use the packageName of diceGames, so we use,

package diceGames;

From now on we're going to have our @Test methods in a separate class to our code under test.  This is because previously our @Test methods have been part of the class we're testing, which means they rely on the same constructor.  If we're going to make new constructors, we need our @Test methods not to be dependent on them - they really object when you change the default constructor, error below,..

"this" ... this what?

Another item we're introducing is the this. keyword.  We can use this inside methods where we call other methods or use attributes of the class.  The this. keyword refers to the current instance of the object.

So we could for instance have written ...

As ...

And ...

As ...

Usually it doesn't make much difference.  But for constructors it's pretty important.

Our first constructor!

A constructor is a method - but one rather unique, because you don't specify a return value (the object after all is the return value).

Constructors have the same name as their class - so for our class diceClass, we declare a constructor as,

public DiceClass (int sides);

Constructors have to be public (they are after all going to be called outside of the class).  As you can see I can pass parameters in - for this, I'm using an integer number called sides to set how many sides I want.

Here's the @Test method I'm using (under the same package, but in a different class).

You can see here it calls DiceClass(20), passing 20 to make a 20-sided dice.  This produces ...

Looking good!

Overloaded constructor

Here's the thing, most of the time people when they mean a dice, they mean a 6-sided dice.  I suppose I could always call DiceClass(6).  But I'm too lazy to.

Sometimes you need more than one method, which will do a similar job.  In Java it's possible to have multiple methods with the same name - this is called overloading.

There is a catch though - each method has to be called with a unique combination of data type - so for our diceClass example we could have the following constructors and they'd all play nice,

public DiceClass (int sides);
public DiceClass (int sides, int number);
public DiceClass (String diceName);
public DiceClass (double dimEnsion);
public DiceClass ();

You'll notice you can call with one integer or two integers - because the combination is unique.

However if you use the same data type, it will fail to build, even if you give them different variable names being passed.  So this won't work ...

public DiceClass (int sides);
public DiceClass (int number);
We already have a constructor for which we pass an integer - I want to define one where we don't pass one ...

public DiceClass ();

The code for this constructor is going to look like this ...

Our @Test class will differ only in that it'll use DiceClass() without an argument being passed.

This works perfectly as expected!

Calling one constructor ... from inside another constructor

Here's the thing - the new constructor works okay ... but I know I've created two now which I'll have to maintain in the long run.  Darn!

There's a fix for this - and why we've started to use the this keyword.

Within my default DiceClass() constructor, I can use the this keyword to call another constructor by using it as a method caller for the class constructor.  I can do this by writing the following code

Here this(6) is basically behaving as if DiceClass(6) was being called ...

The code is available in Github here.

Do we need to define our own constructors?

It's not always crucial.  But just remember that if you don't, then your attributes aren't set to initial value - maybe that matters, maybe it doesn't.  It all depends on your class.

This way, we don't have to remember to set the number of sides on the dice every time we call one - which is cleaner.  If we forget to set one, it'll be set to 6-sided, which is a good default.

Extension material

Download a copy of the DiceClass, and try making the constructors private.  What happens?

We looked at some important, and complex topics today, you might want to look more into
  • packages
  • this
  • overloading
Remember, Google is your friend!


  1. Congratulations guys, quality information you have given!!!..Its really useful blog. Thanks for sharing this useful training in chennai | chennai's no.1 java training in chennai | best java institute in chennai

  2. Nicely explained. Here you described the well written article from your in-depth knowledge. Truly impressive and nice information

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

  3. Nice and well mentioned, wonderful article to clear all of doubts to me. Thank you for your information.
    Java Training in chennai

  4. Play the latest online gambling game industry.

    รูบี้888 Is a website that offers online gambling services, a new online gambling game that makes online gambling games easier to play because of the game. Online gambling is fun. And the ability to play online gambling games of the player is very much because playing online casino games is different from playing a game of casino games in general.

    By the side of the player will play online casino games through the computer screen with the latest online gambling games to change the view. And online gambling games that players never seen in the past. By default, gamble through this online system. It's like playing online games online. Have fun, have a lot of games to choose from the games you like to play the game.

    And all important online gambling games can be played every day, no need to download the program, just have the Internet to play all the games and then play online casino games on the casino site. This club is a pleasure. The player and your friends can join and start playing online gambling games easily at the web รอยัล1688

  5. This looks absolutely perfect. All these tiny details are made with lot of background knowledge. I like it a lot. 
    Java training in Chennai | Java training in Bangalore

    Java online training | Java training in Pune

  6. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Data Science course in Indira nagar
    Data Science course in marathahalli
    Data Science Interview questions and answers

  7. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.
    python interview questions and answers
    python tutorials
    python course institute in electronic city

  8. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    Best Devops training in sholinganallur
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram

  9. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

    angularjs interview questions and answers

  10. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.
    Devops Training in bangalore
    Digital Marketing Training in bangalore
    Data Science Training in bangalore
    Java Training in bangalore

  11. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.
    Devops Training in bangalore
    Digital Marketing Training in bangalore
    Data Science Training in bangalore
    Java Training in bangalore

  12. Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
    best java training in coimbatore
    php training in coimbatore

  13. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.Informatica Training in Bangalore

  14. Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site.MSBI Training in Bangalore

  15. Awesome,Thank you so much for sharing such an awesome blog.Big Data Training in Marathahalli

  16. Thanks for sharing this blog. This very important and informative blog.Tableau Training in Bangalore

  17. Learned a lot of new things from your post! Good creation and HATS OFF to the creativity of your mind.Hadoop Training in Bangalore

  18. Great post!I am actually getting ready to across this information,i am very happy to this commands.Also great blog here with all of the valuable information you have.Well done,its a great knowledge.

    sap abap training in bangalore

    sap abap courses in bangalore

    sap abap classes in bangalore

    sap abap course syllabus

    best sap abap training

    sap abap training center

    sap abap training institute in bangalore

  19. Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site...
    Digital Marketing Courses in Bangalore

  20. It is amazing and wonderful to visit your site.Thanks for sharing this information...
    Informatica Bangalore

  21. Effective blog with a lot of information. I just Shared you the link below for Courses .They really provide good level of training and Placement,I just Had Java Classes in this institute , Just Check This Link You can get it more information about the Java course.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery