[TUTORIAL] JAVA - Building and using a class

Find all FAQs, HOWTOs and guides here.
Forum rules
READ NOW: L2j Forums Rules of Conduct
Post Reply
User avatar
Posts: 1384
Joined: Tue Aug 12, 2008 2:28 am
Location: Quebec, Canada

[TUTORIAL] JAVA - Building and using a class

Post by theone » Thu Jun 03, 2010 6:59 am

This tutorial is meant as a prelude to a future "Build your own quests in Java" tutorial.
It's essential that you understand how Java classes work before you go and try to build Quests and AI (unless you just do some copy-paste and modify a few things, but it has its limitations :) )

1- Basic Java class structure:
First of all, if you are using an IDE(Eclipse, Netbeans, etc...), and you should, when you create a new class some informations will be put into it automatically for you. i.e.: you will not start with a completely blank page.

When you create a class, lets call it MyTutorialClass, it should look like this at first:

Code: Select all

package base; public class MyTutorialClass{ } 
The "package base;" part specify where your class is located in the structure of an application
Now this part is the most important:

Code: Select all

public class MyTutorialClass{ }
It's within this part that you will create all the methods, variables, etc, that you will be able to use.
If you put something outside the last "}" it will not only not work, but it will also give an error.

Lets create some variables and methods.
We will say, for the sake of this tutorial, that the class will contain 2 variables:
- The name of the student (String)
- The student's current score, based on a 30 maximum (int)
As we will be accessing these variables only from inside this class, we will set them as "private"
This is the current result:

Code: Select all

public class MyTutorialClass{    private String name;    private int score = 0;}
Ok, the name variable is not initialized, which means that if we were to try to access it, we would get a "NullPointer" exception.
:shock: What the hell is a nullpointer???
A nullpointer happens when we try to access something that has a "null" value(no value) and/or a variable that has not been intialized. It's something very important to remember as it's the error you will be getting most often when programming. When coding, always ask yourself this question: "Is there a chance that this particular variable or method will return a null value when it's accessed? And if so, how do I prevent errors?"
Now back on subject...
Lets prevent getting errors when accessing the "name" variable.
The first step we will take is by making sure that it's initialized as soon as the class is instantiated. To do so, we will make sure that this data is passed to the class on instantiation. We will override the "new MyTutorialClass();" method and change it to: "new MyTutorialClass(name);"
Here is how we do this:

Code: Select all

public class MyTutorialClass{    public MyTutorialClass(String name)    {        this.name = name;    }    private String name;    private int score = 0;}
We have just made sure that the variable will get initialized when the class is instantiated.
Now lets create some methods to retrieve and modify the variables that we have in the class.
Lets start with the "score" variable and create 3 methods:
- The first one will update the score with a new value
- The second will get a percentage value representing the score, as a "double", which means that there will be decimals.
- The third will be used to retrieve the name of the student

Code: Select all

public class MyTutorialClass{    public MyTutorialClass(String name)    {        this.name = name;    }    private String name;    private int score = 0;     public void updateScore(int score)    {        this.score = score;    }     public double getScorePercent()    {        double percent = ((double)score/30)*100;    }     public String getName()    {        if(name != null)        {            return name;        }        return "Unknown";    }}
I had to "cast" the "score" variable to a double in order to make sure that the result would be also a double(with decimals). If I had not done this, the result would have been an integer "cast" to a double, in other words there would not have been decimals.
The getName() method should be of interest to you. I added an "if" statement which checks if the "name" variable is not null.
If it's not null, it returns its value, if it's null, it returns "Unknown" instead. This check is there to avoid nullpointers.

2- getInstance() ... I see this all over the place, what the hell is that?
The getInstance() method is used to retrieve the instance of a class which is supposed to be instantiated only once.
It's meant to do so easily, without the need to store the instance of this class in each and every single other class that might use this class.
There are 3 ways(that I know of) to access a class which has a single instantiation from another class. 2 of them use getInstance() and are quite similar in nature. We'll start with the 3rd one :mrgreen:

Using injections:
I wont stay very long on the injections subject as it's quite advanced stuff, just know that it exists. You can seamlessly inject the instance of a class into another class(and a whole lot more things than that) without the need to use getInstance() or storing that class's instance.
If you're interested in reading/learning about it, I suggest you read this: http://code.google.com/p/google-guice/

Ok, now lets get to the 2 other methods:
The first one is the one used in L2J. It's safe and efficient and uses singletons. I'm not going to get into details so much into this one either. You can take a look at most classes in the L2J core to figure out how to do it.
The second method is the simplest one to implement and can be made safe if you do a check for nullpointers (fyi: nullpointers are the reason why L2J started using singletons a while back if I remember correctly).
This method is very simple and is done like so:

Code: Select all

public class MyTutorialClass{    private static MyTutorialClass instance = null;     public static MyTutorialClass getInstance()    {        if(instance == null)        {            instance = new MyTutorialClass();        }        return instance;    }}
This is the method that I usually use, but L2J's method is very safe, so which ever one works for you will be fine.

3- Accessing a class from another one:
There are 2 ways that you can access or instantiate a class from another one.
First and foremost, do not forget to import the class that you want to call or instantiate into the other class :mrgreen:
Now that it's been imported, we can either call it(if it's a single instantiation class) or create a new instance of it, if that's what we need.
Lets see how we do both:

Code: Select all

MyTutorialClass myClass = MyTutorialClass.getInstance();

Code: Select all

MyTutorialClass myClass = new MyTutorialClass("John Smith");
And that's all there is to it basically!
Now that you have the(an) instance of that class, you can use all its public methods from the other class!
A good example of this is when you do: player.setHp(1000);
The setHp method is located in the L2PcInstance class (or is it L2Character?? anyway, L2PcInstance extends L2Character so in the end it's the same result :) )
You can call the setHp method because your "player" is an instance of L2PcInstance, and by extension of L2Character.

Well I think this pretty much covers the basics. Happy coding everyone!

User avatar
Posts: 1392
Joined: Wed May 30, 2007 9:13 pm
Location: Russia

Re: [TUTORIAL] JAVA - Building and using a class

Post by denser » Thu Jun 03, 2010 7:55 am

thx TheOne, it dig me a little bit deeper to understanding of principles how to :)
Tiger, once tasted human flesh, will want to taste it again
L2J - the place where glad to see you any time!

Post Reply