Methods are declared in the following way in Java:
MethodModifiers ResultType Identifier ( [ParameterList]
) [throws ExceptionList]
where
-
MethodModifiers - These supply extra information to the compiler about
the method. They can be :
-
public - This specifies that the method can be called by any class
-
protected - This specifies that the method can only be accessed
by this class and any of it's sub-classes.
-
private - This specifies that the method can only be accesed by
this class.
-
abstract - A method marked as abstract does not have any body. If
a class has abstract methods then the class must be marked as being abstract
as well. Objects cannot be created for an abstract class.
-
static - A static method is a method that can be called on
the class. All other methods have to be called on an object of the class.
A static method can only call other static methods on the class and can
only access static attributes of the class. The void main method is an
example of a static method.
-
final - If a method is declared as being final then sub-classes
of the class cannot override the method.
-
synchronized - If a method is declared as being synchronized then
a lock on the object must be acquired before the method can be called.
This is used for multithreading so that thread safe code can be written.
Only one thread can have a lock on a particular object at anytime. Any
thread calling a method on a locked object, waits until the lock it released.
-
native - This specifies that the method calls platform dependent
code. This code is normally written in another language such as C or C++.
-
ResultType - This specifies the type of data that is returned by the method.
If the method does not return anything then a result type of void
should be specified.
-
Identifier - This is the name of the method.
-
ParameterList - This is the list of parameters that the method accepts.
It is optional. Each parameter is separated by a comma and is declare as
a Type Identifier pair.
-
ExceptionList - The exception list is the list of exceptions that the method
could throw. Any code calling this method must make provisions for catching
the exceptions specified in the exceptions list.
The following is some examples of method declarations:
public class MyMethods
{
protected static long Counter = 0; // declare static counter set to 0
public void procOne() // simply method no parameters, no result.
{
//...code here
}
public int addNumbers(int numberOne, int numberTwo) // methods takes to integers, adds them and returns result
{
return numberOne + numberTwo;
}
public static synchronized long getCounter() // thread safe method returns counter. Can be called on class
{
return counter;
}
}
Sources