7. Methods
A method is series of statements combined into one block inside a class and given a name. In the Cold War days, these were called “sub-routines” and many other languages call them functions. However, the main difference between a method and a function is that a method needs to be associated with a class whereas a function does not.
7.1 Call me
Methods exist to be called. You can think of a method as a message that is sent or a command given.
To call a method (also called invoking a method), you simply write the name of the object, a dot, then the method name. For example:
1 Dragon dragon = new Dragon();
2 dragon.fly(); // dragon is the object, and fly is the method
The fly method would be defined within the Dragon class.
1 public void fly() {
2 // flying code
3 }
|
VoidIn Java, |
Methods can also have parameters. A parameter is a value (or reference value) that is part of a method call. Together, the method’s name and parameters are called the method signature. For example, the following method has two parameters:
1 public void fly(int x, int y) {
2 // fly to that x, y coordinate.
3 }
Non-Java
Other languages define methods (or functions) differently.
For example, in Groovy you can use the def keyword to define a method (in addition to Java’s normal syntax):
1 def fly() { println("flying") }
Scala also uses the def keyword to define a method, but you also need an equals (=) sign.
1 def fly() = { println("flying") }
JavaScript uses the function keyword to define a function:
1 function fly() { alert("flying") }
7.2 Break it down
Methods also exist to organize your code. One rule of thumb is to never have a method that is longer than one screen. It makes no difference to the computer, but it makes all the difference to humans (including you).
It’s also very important to name your method well. For example, a method that fires an arrow should be called “fireArrow”, and not “fire”, “arrow”, or “arrowFartBigNow”.
This may seem like a simple concept, but you might be surprised how many people fail to grasp it.
7.3 Return to sender
Many times you will want a method to return a result.
In Java, you use the return keyword to do this.
For example:
1 public Dragon makeDragonNamed(String name) {
2 return new Dragon(name);
3 }
Once the return statement is reached, the method is over. Whatever code called the method will resume execution.
In some languages, like Groovy and Scala, the return keyword is optional.
Whatever value is put on the last line will get returned.
For example (groovy):
1 def makeDragonNamed(name) {
2 new Dragon(name)
3 }
7.4 Static
In Java, a static method is a method which is not linked to an object instance. However, it must be part of a class.
For example, the random() method in the java.util.Math class we learned about earlier is a static method.
To declare a static method, you simply add the word static, as in:
1 public static String makeThemFight(Dragon d, Vampire v) {
2 // a bunch of code goes here.
3 }
Since Java is an Object-Oriented programming language, in theory, static methods should be used sparingly (since they are not linked to any “object”). However, in real-life you will see them a lot.
7.5 Varargs
Varargs or “Variable Arguments.”
You can declare a method’s last parameter with an ellipsis (...) and it will be interpreted to accept any number of parameters (including zero) and convert them into an array in your method.
For example, see the following code:
1 void printSpaced(Object... objects) {
2 for (Object o : objects) System.out.print(o + " ");
3 }
Putting it all together, you can have the following code (with output in comments):
1 printSpaced("A", "B", "C"); // A B C
2 printSpaced(1, 2, 3); // 1 2 3
7.6 Main method
Now that you know about static methods, you can finally run a Java program (sorry it took so long).
Here’s how you create an executable main method in Java:
1 import static java.lang.System.out;
2 /** Main class. */
3 public class Main {
4 public static void main(String ... args) {
5 out.println("Hello World!");
6 }
7 }
Then to compile it, open your “command prompt” or “terminal” and type:
1 javac Main.java
2 java Main
Or from NetBeans:
- Right-click on the Main class.
- Choose “Run File”
7.7 Exercises
|
Try out methodsAfter you’ve created the |
|
Lists, Sets, and MapsIn Java, all of these data structures are under the Then, go back the chapter on Lists, Sets, and Maps, and try out some the code there. |
7.8 Summary
This chapter explained the concept of methods and how they should be used.
We also put together everything you’ve learned up to this point and made a small Java application.