Java Chapter 7 - Writing Methods
7.1 Basic Methods
Within a class, you can have many methods (functions). You may create methods to put code into reusable containers. Putting code in methods can also make the main program simpler and more readable. Below is an example program with three methods.
methods.java |
public class
methods { public static void main (String[] args) { PrintIntro(); PrintConclusion(); } public static void PrintIntro() { System.out.println("This is the introduction"); } public static void PrintConclusion() { System.out.println("This is the conclusion"); } } |
Output This is the introduction This is the conclusion |
When your primary class has multiple methods, the entry point of the program is the method named main.
Static keyword: The word "static" means that the method can be used without declaring an instance of the object (class). This is usually the case for methods used as functions in the main class.
7.2 Methods that Send and Return Data
The program below demonstrates using a method that you send data to and returns a value.
paycheck.java |
// This
program demonstrates sending data to a method and returning a value.
public class paycheck |
Output Total Pay = 36.0 |
Let's examine the format of the header line of the CalculatePay method:
public | static | double | CalculatePay | double Hours | double Wage |
public: Any class can access this
method. private: Only other methods in this class can access this method. |
With this keyword, this method can be used without declaring and instance of the object/class. | The method returns a number of type double. If the method doesn't return data, this should be void. | The name of the method. | Declare a variable to store the first parameter. | Declare a variable to store the second parameter. |
You may define two or methods that share the same name within a class, as long as the parameters are different. The parameters can be different in type and/or the number of parameters. For example, you could have methods that calculate the average of numbers.
overload.java |
// This
program demonstrates overloading methods // If you call Average() with 2 parameters, the first method is used // If you call Average() with 3 parameters, the second method is used
public class overload |
Output 7.5 10.0 |