07. From UML to code

So you might recall our UML diagram that explained the general structure of our Card class, it looks like this:

The top section of that diagram represents the name of our class, the middle section represents all the Fields we require and the bottom section holds any Methods or behaviours this class provides. So converting to Java code should be relatively simple.

We’ll start with the Fields. Add the following code under the commented section titled “MEMBER VARIABLES“:

private final String suitColour;
private final String suitName;
private final int suitRank;
private final String cardName;
private final int cardRank;

You can see here we’ve given our fields appropriate data types and really, this is not much different to any procedural programming language. The only thing you might find a bit peculiar are the words “private” and “final“. These will be explained later.

Now let’s add our method under the “METHODS” comment:

public String printCardVal() {

}

Once again, really not that different to procedural programming. We’ve defined a method called “printCardVal” that takes no parameters and returns a value of type “String“. Notice that in Java we don’t separate procedures from functions, all sub-routines are known as methods, if they return something then they have a return type (like this one), if they don’t then their return type is “void” (we’ll see an example of this later.)

Now that you’ve copied that in, you’ve probably also noticed the sensitivity of Eclipse:

Eclipse is pretty good at finding your errors and suggesting ways to fix them so while it might seem annoying to be constantly reminded of where you’re going wrong, it’ll help you get things right in the long run.

We’ll start by fixing the error on line 21. This has occurred simply because this method is supposed to return a value of type String and it hasn’t. While we don’t have anything useful to return right now, let’s at least stop this thing from erroring (I’m copyrighting that word BTW!) To fix the error just add the following line inside our method:

return "";

Done! The other errors listed are because of our empty Constructor and Fields. This is probably a good point to stop and explain Constructors.

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>