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!

10 comments:

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

    ReplyDelete
  2. 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

    ReplyDelete
  3. 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

    ReplyDelete
  4. 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

    ReplyDelete
  5. 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

    ReplyDelete
  6. 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

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

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

    ReplyDelete
  9. PC networks are the premise of correspondence in IT. They are utilized in a tremendous assortment of ways and can incorporate a wide range of kinds of organization.
    Computer network

    ReplyDelete