Pallet Town: OO with Pokemon and Java pt2

Nov 11, 2013 | Java, Pallet Town, Programming

Welcome to Pallet Town! Pallet town is going to be an ongoing bi-weekly look at various development technologies and techniques from the perspective of someone new to that technology. For those who might know or (God forbid) are too young to get the reference, Pallet Town is the first town in the original Pokemon games for the Nintendo Gameboy.

Ok, so we are picking up where we left off in our last post. We have a basic Pokemon class:


public Class Pokemon {     

    public int id;    
    public String name;
    public int hp;
    public int ap;
}

We also have learned how to construct a Pokemon based on our existing class:


Pokemon pikachu = new Pokemon();

And of course how to set some properties for our new pikachu:


Pokemon pikachu = new Pokemon();

pikachu.name = "Pikachu";
pikachu.ap = 10;
pikachu.hp = 100;

That of course works, but is a little bit of a pain. Let’s take things a step further and make a more convenient constructor for our Pokemon class:


public Class Pokemon {     

    public int id;    
    public String name;
    public int hp;
    public int ap;

    public Pokemon(int _id, String _name, int _hp, int _ap) {
        this.id = _id;
        this.name = _name;
        this.hp = _hp;
        this.ap = _ap;

        return this;
    }
}

I know that might look a little crazy but it is actually pretty simple. Basically, we are setting values for the properties of our Pokemon in the constructor itself rather than having to do so in the implementation — this is a very primitive form of encapsulation, one of the most important concepts of all of software development. So, using our new constructor, we’d create the same pikachu from before:


Pokemon pikachu = new Pokemon(14, "pikachu", 100, 10);

Doesn’t that look much cleaner?

Hope this post helps you on your journey to become a Pokemon… err coding master! Please feel free to send any feedback to me on Twitter or Google+. Also, be sure to check out my company Fingertip Tech, INC on Twitter.

 

More from Mike:

About Me

Hi! I’m Mike! I’m a software engineer who codes at The Mad Botter INC. You might know me from Coder Radio or The Mike Dominick Show.  Drop me a line if you’re interested in having some custom mobile or web development done.

Follow Me

© 2024 Copyright Michael Dominick | All rights reserved