Merge pull request #28420 from lkxed/20230110-3-How-to-use-methods-in-Java

[手动选题][tech]: 20230110.3 ️ How to use methods in Java.md
This commit is contained in:
Xingyu.Wang 2023-01-13 09:15:13 +08:00 committed by GitHub
commit f4347ec8b6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,187 @@
[#]: subject: "How to use methods in Java"
[#]: via: "https://opensource.com/article/23/1/java-methods"
[#]: author: "Seth Kenlon https://opensource.com/users/seth"
[#]: collector: "lkxed"
[#]: translator: " "
[#]: reviewer: " "
[#]: publisher: " "
[#]: url: " "
How to use methods in Java
======
A method in Java (called a "function" in many other programming languages) is a portion of code that's been grouped together and labeled for reuse. Methods are useful because they allow you to perform the same action or series of actions without rewriting the same code, which not only means less work for you, it means less code to maintain and debug when something goes wrong.
A method exists within a class, so the standard Java boilerplate code applies:
```
package com.opensource.example;
public class Example {
// code here
}
```
A package definition isn't strictly necessary in a simple one-file application like this, but it's a good habit to get into, and most IDEs enforce it.
By default, Java looks for a `main` method to run in a class. Methods can be made public or private, and static or non-static, but the main method must be public and static for the Java compiler to recognize and utilize it. When a method is public, it's able to be executed from outside the class. To call the `Example` class upon start of the program, its `main` method must be accessible, so set it to `public`.
Here's a simple demonstration of two methods: one `main` method that gets executed by default when the `Example` class is invoked, and one `report` method that accepts input from `main` and performs a simple action.
To mimic arbitrary data input, I use an if-then statement that chooses between two strings, based on when you happen to start the application. In other words, the `main` method first sets up some data (in real life, this data could be from user input, or from some other method elsewhere in the application), and then "calls" the `report` method, providing the processed data as input:
```
package com.opensource.example;
public class Example {
public static void main(String[] args) {
// generate some data
long myTime = System.currentTimeMillis();
String weather;
if ( myTime%2 == 0 ) {
weather = "party";
} else {
weather = "apocalypse";
}
// call the other method
report(weather);
}
private static void report(String day) {
System.out.printf("Welcome to the zombie %s\n", day);
}
}
```
Run the code:
```
$ java ./Example.java
Welcome to the zombie apocalypse
$ java ./Example.java
Welcome to the zombie party
```
Notice that there are two different results from the same `report` method. In this simple demonstration, of course, there's no need for a second method. The same result could have been generated from the if-then statement that mimics the data generation. But when a method performs a complex task, like resizing an image into a thumbnail and then generating a widget on screen using that resized image, then the "expense" of an additional component makes a lot of sense.
### When to use a Java method
It can be difficult to know when to use a method and when to just send data into a [Java Stream][1] or loop. If you're faced with that decision, the answer is usually to use a method. Here's why:
- Methods are cheap. They don't add processing overhead to your code.
- Methods reduce the line count of your code.
- Methods are specific. It's usually easier to find a method called `resizeImage` than it is to find code that's hidden in a loop somewhere in the function that loads images from the drive.
- Methods are reusable. When you first write a method, you may _think_ it's only useful for one task within your application. As your application grows, however, you may find yourself using a method you thought you were "done" with.
### Functional vs. object-oriented programming
Functional programming utilizes methods as the primary construct for performing tasks. You create a method that accepts one kind of data, processes that data, and outputs new data. String lots of methods together, and you have a dynamic and capable application. Programming languages like C and [Lua][2] are examples of this style of coding.
The other way to think of accomplishing tasks with code is the object-oriented model, which Java uses. In object-oriented programming, methods are components of a template. Instead of sending data from method to method, you create objects with the option to alter them through the use of their methods.
Here's the same simple zombie apocalypse demo program from an object-oriented perspective. In the functional approach, I used one method to generate data and another to perform an action with that data. The object-oriented equivalent is to have a class that represents a work unit. This example application presents a message-of-the-day to the user, announcing that the day brings either a zombie party or a zombie apocalypse. It makes sense to program a "day" object, and then to query that day to learn about its characteristics. As an excuse to demonstrate different aspects of object-oriented construction, the new sample application will also count how many zombies have shown up to the party (or apocalypse).
Java uses one file for each class, so the first file to create is `Day.java`, which serves as the Day object:
```
package com.opensource.example;
import java.util.Random;
// Class
public class Day {
public static String weather;
public int count;
// Constructor
public Day() {
long myTime = System.currentTimeMillis();
if ( myTime%2 == 0 ) {
weather = "paradise";
} else {
weather = "apocalypse";
}
}
// Methods
public String report() {
return weather;
}
public int counter() {
Random rand = new Random();
count = count + rand.nextInt(100);
return(count);
}
}
```
In the `Class` section, two fields are created: `weather` and `count`. Weather is static. Over the course of a day (in this imaginary situation), weather doesn't change. It's either a party or an apocalypse, and it lasts all day. The number of zombies, however, increases over the course of a day.
In the `Constructor` section, the day's weather is determined. It's done as a [constructor][3] because it's meant to only happen once, when the class is initially invoked.
In the `Methods` section, the `report` method only returns the weather report as determined and set by the constructor. The `counter` method, however, generates a random number and adds it to the current zombie count.
This class, in other words, does three very different things:
- Represents a "day" as defined by the application.
- Sets an unchanging weather report for the day.
- Sets an ever-increasing zombie count for the day.
To put all of this to use, create a second file:
```
package com.opensource.example;
public class Example {
public static void main(String[] args) {
Day myDay = new Day();
String foo = myDay.report();
String bar = myDay.report();
System.out.printf("Welcome to a zombie %s\n", foo);
System.out.printf("Welcome to a zombie %s\n", bar);
System.out.printf("There are %d zombies out today.\n", myDay.counter());
System.out.printf("UPDATE: %d zombies. ", myDay.counter());
System.out.printf("UPDATE: %d zombies. ", myDay.counter());
}
}
```
Because there are now two files, it's easiest to use a Java IDE to run the code, but if you don't want to use an IDE, you can create your own [JAR file][4]. Run the code to see the results:
```
Welcome to a zombie apocalypse
Welcome to a zombie apocalypse
There are 35 zombies out today.
UPDATE: 67 zombies. UPDATE: 149 zombies.
```
The "weather" stays the same regardless of how many times the `report` method is called, but the number of zombies on the loose increases the more you call the `counter` method.
### Java methods
Methods (or functions) are important constructs in programming. In Java, you can use them either as part of a single class for functional-style coding, or you can use them across classes for object-oriented code. Both styles of coding are different perspectives on solving the same problem, so there's no right or wrong decision. Through trial and error, and after a little experience, you learn which one suits a particular problem best.
--------------------------------------------------------------------------------
via: https://opensource.com/article/23/1/java-methods
作者:[Seth Kenlon][a]
选题:[lkxed][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
[a]: https://opensource.com/users/seth
[b]: https://github.com/lkxed
[1]: https://opensource.com/article/20/1/javastream
[2]: https://opensource.com/article/22/11/lua-worth-learning
[3]: https://opensource.com/article/19/6/what-java-constructor
[4]: https://opensource.com/article/21/8/fastjar