Special Effects and Game Development
in Java(TM) - Methods,classes and references
by Anibal Wainstein
1.3 Methods, classes
and references
Note that my review of object oriented programming is adapted
to the practical use that I see in it, therefore I will not
write about strict object oriented theory.
1.3.1 Methods
A method is a bit of Java code that is executed only when
called (in other languages they are the equivalent to functions).
It may also contain variable declarations which are only valid
within the method. These variables are therefore called local
variables. A method is defined by the method header and two
brackets "}{":
public void myMethod()
{
}
The word public indicates that the method can be called
by other classes, void indicates that the method does
not return a value when it has finished the execution and "myMethod"
is the name of the method. You can put variables within the
parenthesis () that must be delivered by the user when calling
the method in order for it to work. This particular function
do not happen to have any variables. Another example :
public int yourMethod(int a, int b)
{
a+=b;
return a;
}
If the method returns anything then "return" must
always be specified. In this particular case the method
will return an integer int which is the sum of the variables
"a" and "b". The function is called like
this:
//We declare the "result" variable
int result;
//"result" will contain
//the number 3 after the calculation result = yourMethod(1,2);
Another example:
private byte anotherMethod(int a)
{
return ((byte) a);
}
Private indicates that method may only be used within
the class where it has been defined. In the return part you
can also have calculations even if it is not so beautiful but
this gives a more compact code (less code). In this example
we type cast the integer "a" to a byte and return
it. The method is called like this:
//"a" will contain the number 41
byte a = anotherMethod(1234217);
This is by the way the same as:
byte a;
a = anotherMethod(1234217);
When
you convert a 32 bit integer to a byte then only the last
8 bits in the number will be left (the 8 last bits in 1234217
has the value 41). Please note that if you do not specify
a returnation object then the method is called a constructor.
It must have the same name as the class and it will be called
when you create an object of the class. A constructor must
always be declared as public:
public myklass(int a)
{
a++
}
Next Page >>
|