© Adam L. Davis 2020
A. L. DavisModern Programming Made Easyhttps://doi.org/10.1007/978-1-4842-5569-8_7

7. Methods

Adam L. Davis1 
(1)
Oviedo, FL, USA
 

A method is a 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 has to be associated with a class, whereas a function does not.

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 known as invoking a method), you typically 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   }

../images/435475_2_En_7_Chapter/435475_2_En_7_Figa_HTML.jpg Void In Java, void means that although the method might do many things, no result is returned.

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, return type, 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), as follows:
1   def fly() { println("flying") }
Scala also uses the def keyword to define a method, but you also need an equal (=) sign.
1   def fly() = { println("flying") }
JavaScript uses the function keyword to define a function:
1   function fly() { alert("flying") }

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 “arrowBigNow.”

This may seem like a simple concept, but you might be surprised by how many people fail to grasp it. It also might be overlooked when you are in a hurry. If you don’t name a thing well, it will make your life (and that of other programmers working with you) harder in the future.

Return to Sender

Often, 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 complete. Whatever code called the method will resume execution. If there is a return type (like the preceding Dragon), the method can return a value of that type and it can be used by the calling code (the preceding method returns a new Dragon object ).

In some languages, such as Groovy and Scala, the return keyword is optional. Whatever value is put on the last line of the method will be returned. For example, in Groovy the following code is acceptable:
1   def makeDragonNamed(name) {
2           new Dragon(name)
3   }

Static

In Java, a static method is a method that is not linked to an object instance. It cannot refer to non-static fields of the class it is defined in. 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 the following code:
1   public static String getWinnerBetween(Dragon d, Vampire v) {
2           return "The Dragon wins";
3   }

For example, if the preceding method is defined in a class named Fight, it could be called from another class as Fight.getWinnerBetween(dragon, vampire) where dragon is an instance of a Dragon and vampire is an instance of a Vampire.

Because Java is an object-oriented programming (OOP) language (as well as Scala and Groovy), static methods should be used sparingly, because they are not linked to any object instance. However, they can be useful in many circumstances. For instance , they can be useful for “factory” methods (methods which create objects). The method makeDragonNamed() defined previously is a good example of a factory method. Static methods can also be useful for code that is used from many different classes; java.util.Arrays.asList() is an example—it takes any number of parameters and returns a new List containing those values.

Varargs

Varargs, or “variable arguments ,” allow you to declare a method’s last parameter with an ellipsis (...), and it will be interpreted to accept any number of parameters of a given type (including zero parameters) 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

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 (the class name can be different, but the main method must have this signature in order for Java to execute it):
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 the following:
1   javac Main.java
2   java Main

In the groovyConsole, just press Ctrl+R.

Or in NetBeans, do the following:
  • Right-click the Main class.

  • Choose Run File.

Exercises

../images/435475_2_En_7_Chapter/435475_2_En_7_Figb_HTML.jpg Try out methods. After you’ve created the Main class, try adding some methods to it. Try calling methods from other methods and see what happens.

../images/435475_2_En_7_Chapter/435475_2_En_7_Figc_HTML.jpg Lists, Sets, and Maps In Java, all of these data structures are under the java.util package. So, start by importing this whole package:

1   import    java.util.*;

Then go back to Chapter 5 and try out some of the code there.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset