|
C++ programmers should take note that both methods are defined inside the class definition. Once again we see that in Java everything belongs to a class.
Let's take a closer look at the syntax of a method: static long factorial (int n) { int i; long result=1; for (i=1; i <= n; i++) { result *= i; } return result; } Methods begin with a declaration. This can include three to five parts. First is an optional access specifier which can be public, private or protected. A public method can be called from pretty much anywhere. A private method can only be used within the class where it is defined. A protected method can be used anywhere within the package in which it is defined. Methods that aren't specifically declared public or private are protected by .
Next we decide whether the method is or is not static. Static methods have only one instance per class rather than one instance per object. All objects of the same class share a single copy of a static method. By methods are not static.
Next we specify the return type . This is the value that will be sent back to the calling method when all calculations inside the method are finished. If the return type is int, for example, we can use the method anywhere we use a constant integer. If the return type is void then no value will be returned.
Next is the name of the method.
Then there are parentheses. Inside the parentheses we give names and types to the arguments of the method. A method may have no arguments or it may have one or several. These arguments can be used inside the method just like local variables.
Finally the rest of the method is enclosed in braces to make it a single block. The part inside braces is just like the main methods we've been exploring till now. There are variable declarations, some code, and finally something new, a return statement. The return statement sends a value back to the calling method. The type of this value must match the declared type of the method.
In general any line that looks like Text(arg1, arg2) or text(arg1) or text() is a method call. The compiler is responsible for distinguishing between parentheses that mean method calls and parentheses that serve as grouping operators in mathematical expressions like (3 + 7) * 2. The compiler does a very good job of this and you may safely assume that anything that isn't clearly an arithmetical expression is a method call.
Methods break up a program into logically separate algorithms and calculations. In still larger programs it's necessary to break up the data as well. The data can be separated into different classes and the methods attached to the classes they operate on. This is the heart of object oriented programming and the subject of Chapter 4 below.
|