Well, if you're reading this, you most likely do not have a lot of Java experience. No offense to anyone that reads this that DOES have a bit of experience, but this is just a basic concept.
Well, let's get started.

Now then, classes that have a need of objects...this is what we are going to make.
I'll start with an example that some people like, a Character (for a game) class. Let's start with the basic header for our class and a constructor.
java
class Character
{
public Character()
{
}
}
Well, this is not a very good class yet, since we don't have any data...or methods...or anything besides a constructor...so let's add some! A Character needs HP and MP, right?
java
class Character
{
private int HP;
private int MP;
public Character()
{
}
}
Notice how we declare these private. Declaring them private makes it so that they can only be accessed and/or changed by members of it's own class. (AKA the methods)
Well, now we have data, but it's never initialized, let's add that real quick.
java
class Character
{
private int HP;
private int MP;
public Character(int hp, int mp)
{
this.HP = hp;
this.MP = mp;
}
}
Notice the
this keyword. This is a pointer to the object that is calling the method.
OBJECT.method();, in that case, the
this keyword will reference
OBJECT.
Now we have some HP and MP. Hooray! But now we need some methods to access these variables, right? RIGHT, Locke!
java
class Character
{
private int HP;
private int MP;
public Character(int hp, int mp)
{
this.HP = hp;
this.MP = mp;
}
public int getHP()
{
return this.HP;
}
public int getMP()
{
return this.MP;
}
}
Well, now we have some methods to access our attributes. Notice the return type before the method heading...it NEEDS to be there, so that the method knows what it's supposed to be returning. The return type is always the same as the variable type in basic return methods like these, that just access and tell you what the variable value is.
So if we have something like this...
java
private String name;
public String getName()
{
return this.name;
}
Well, with our
private declaration, we can't change our HP or MP values, only access them with our methods, so let's add some
set methods.
java
class Character
{
private int HP;
private int MP;
public Character(int hp, int mp)
{
this.HP = hp;
this.MP = mp;
}
public int getHP()
{
return this.HP;
}
public int getMP()
{
return this.MP;
}
public void setHP(int newHP)
{
this.HP = newHP;
}
public void setMP(int newMP)
{
this.MP = newMP;
}
}
We MUST have parameters in our
set methods, or Java doesn't know what to set the values to. Notice the
void keyword in the method heading...this means the method doesn't return anything. It doesn't need to, since it's just changing values.
Well, this is just a very basic tutorial in designing Object methods/classes. If you want to know how to make Static classes, you can PM me if my next tutorial does not get approved.
Bye!
This post has been edited by Locke37: 30 Jul, 2008 - 05:47 PM