13. Method creation

The Constructor
We might as well start with the Constructor, it will help make sense of how the other methods will need to function. Copy the following code into your Constructor:

numCards = deckSize;
cards = new Card[numCards];
for (int i = 0; i < numCards; i++) {
   cards[i] = new Card(i);
}
topCard = deckSize - 1;

You can see here we have prepared the deck to be the correct size based on the “deckSize” parameter that was passed in. We’ve then created the array of an appropriate length followed by creating each of the cards that needs to go inside that array.

New
Notice we use the reserved word “new” whenever we are creating an object, this is an important Object-Oriented concept. When we use “new” we are telling our declared object to actually be created. Java will run the constructor of the class we are referencing in order to actually build our object. So any time you see the word “new” just remember that Java then goes and runs the constructor of that class!

The “randomCard” method
This method is pretty self-explanatory but does demonstrate a couple of Java traits you should be aware of. We basically want to return a random number that can map to a card in the deck. Importantly though, it has to be possible to produce every single card!

Random randInt = new Random();
int r = randInt.nextInt();
r = Math.abs(r);
return r % numCards;

There are a couple of new things in this you should be aware of:

  1. External libraries: The “Random” class is not one that is available in every Java project, once you make reference to an external class you will need to make sure it has been imported into your project. The beauty of Eclipse is that it will do it for you if you press “Ctrl-Shift-O“…yet another reason why it’s worth using a good IDE!
  2. Method referencing: If you need to use a method from within an object then you just use a period (.) after the name of your object. So the “nextInt” method belongs to the “Random” class and since “r” is an integer, “nextInt” must return an Integer.
  3. Math:Math” is a generic object that is available in all Java programs. It has many methods available to you but in our case we just want to make sure our integer is a positive number so we’ve used the absolute value method.
  4. Modulus: The modulus function (%) is a handy one that divides the two operands and gives us the remainder. You may have encountered it before…if not, it’s a handy one worth keeping in the back of your mind.

Okay so now our Deck class is taking shape, we have two methods left and we’re done. While they aren’t too complicated we will move to another lesson just because this one has become lengthy…

Leave a Comment

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>