CVGalleryGamesPreviewRandomJavaSiteWeb
Site updates
Testing New System now...

Making Your Own Classes

Of course, if you've ever successfully written and compiled your own program in Java, you've already made a class. This is about making classes with slightly different uses.

Classes to keep your methods and constants in

These are easy to make. For example:

public class doGreatStuff
{
    public boolean isEven(int toTest)
    {
    if((toTest/2*2)==toTest)
        return true;
    else
        return false;
    }
}

Just put any methods and / or constants that you want inside the outer { }s. Remember to declare any constants used in the methods at the top, before they are "used". Declare things public or private as needed.

Making a class that's a useable object

Firstly, you must design the class. Work out what it needs to store inside it, and what processes need to be performed on that data. Remember that it's a bad idea to allow direct access to the data inside, and methods should be provided for reading and writing it instead. This allows you to check any data coming in, and also perform more thorough tests

To implement these, a particular method is needed, called the constructor. This is of the form public <class name>(<??options??>), e.g.:

public class PileOfStuff
{
private int topOfPile;  Variables & constants are always declared first
private int[] thePile;

public PileOfStuff(int pileSize) This method is the constructor
{
topOfPile = 0
thePile = new int[pileSize]
}

//rest of class goes here  Methods to add, read, and manipulate the data

}

If it suits you, you can have several constructors. For example, if you create a noughts & crosses grid class, it would usually represent a 3x3 game. Sometimes, however, you play on a 10x10 grid (because you're odd like that). You could have two constructors, OXOGrid(), and OXOGrid(int xsize , int ysize)

NOTE: The Java section is mostly in maintenence mode. I don't have time to work on it right now. Errors will be corrected if pointed out, but they are not actively being searched for. Newer site features, like alternate stylesheets, may cause problems with these pages.