mirror of
https://github.com/LCTT/TranslateProject.git
synced 2025-02-03 23:40:14 +08:00
translated
This commit is contained in:
parent
db30542211
commit
8ff00c49bd
@ -1,187 +0,0 @@
|
||||
[#]: 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: "ZhangZhanhaoxiang"
|
||||
[#]: 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
|
||||
|
187
translated/tech/20230110.3 ⭐️⭐️ How to use methods in Java.md
Normal file
187
translated/tech/20230110.3 ⭐️⭐️ How to use methods in Java.md
Normal 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: "ZhangZhanhaoxiang"
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
如何在 Java 中使用方法
|
||||
======
|
||||
|
||||
Java 中的方法(在许多其他编程语言中称为“函数”)是被组合在一起并标记为可重用的代码的一部分。方法很有用,因为它们允许您在不重写相同代码的情况下执行相同的操作或一系列操作,这不仅意味着您的工作量减少,还意味着出现问题时需要维护和调试的代码减少。
|
||||
|
||||
类中存在一个方法,因此标准 Java 样板代码适用:
|
||||
|
||||
```
|
||||
package com.opensource.example;
|
||||
|
||||
public class Example {
|
||||
// 在此写代码
|
||||
}
|
||||
```
|
||||
|
||||
在这样一个简单的单文件应用程序中,包定义并不是绝对必要的,但它是一个很好的习惯,而且大多数 IDE 都强制执行它。
|
||||
|
||||
默认情况下,Java 会寻找在类中运行的“main”方法。方法可以是公有的或私有的,也可以是静态的或非静态的,但 main 方法必须是公有的和静态的,Java 编译器才能识别和使用它。当方法是公有的时,它可以从类外部执行。要在程序启动时调用“Example”类,其“main”方法必须是可访问的,因此将其设置为“public”。
|
||||
|
||||
下面是两个方法的简单演示:一个“main”方法在调用“Example”类时默认执行,另一个“report”方法接受“main”的输入并执行简单操作。
|
||||
|
||||
为了模拟任意数据输入,我使用了 if-then 语句,该语句根据您启动应用程序的时间在两个字符串之间进行选择。换句话说,“main”方法首先设置一些数据(在现实生活中,这些数据可以来自用户输入,也可以来自应用程序其他地方的其他方法),然后“调用”“report”方法,将处理后的数据作为输入提供:
|
||||
|
||||
```
|
||||
package com.opensource.example;
|
||||
|
||||
public class Example {
|
||||
public static void main(String[] args) {
|
||||
// 生成一些数据
|
||||
long myTime = System.currentTimeMillis();
|
||||
String weather;
|
||||
|
||||
if ( myTime%2 == 0 ) {
|
||||
weather = "party";
|
||||
} else {
|
||||
weather = "apocalypse";
|
||||
}
|
||||
|
||||
// 调用其他方法
|
||||
report(weather);
|
||||
}
|
||||
|
||||
private static void report(String day) {
|
||||
System.out.printf("Welcome to the zombie %s\n", day);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
运行代码:
|
||||
|
||||
```
|
||||
$ java ./Example.java
|
||||
Welcome to the zombie apocalypse
|
||||
$ java ./Example.java
|
||||
Welcome to the zombie party
|
||||
```
|
||||
|
||||
请注意,同一“report”方法有两个不同的结果。当然,在这个简单的演示中,不需要第二种方法。模拟数据生成的 if-then 语句可能生成了相同的结果。但是,当一个方法执行一项复杂的任务时,比如将图像调整为缩略图,然后使用调整后的图像在屏幕上生成小部件,那么附加组件的“费用”就很有意义了。
|
||||
|
||||
### 何时使用 Java 方法
|
||||
|
||||
很难知道何时使用方法,何时只将数据发送到 [Java 流][1]或循环中。如果你面临这个决定,答案通常是使用一种方法。原因如下:
|
||||
|
||||
- 方法开销少。它们不会给代码增加处理开销。
|
||||
- 方法减少代码的行数。
|
||||
- 方法是特定的。查找名为“resizeImage”的方法通常比查找隐藏在从驱动器加载图像的函数中某个循环中的代码更容易。
|
||||
- 方法是可重用的。当您第一次编写方法时,您可能会 _认为_ 它只对应用程序中的一个任务有用。然而,随着应用程序的编写,您可能会发现自己正在使用一种您认为“已完成”的方法。
|
||||
|
||||
### 函数式编程与面向对象编程
|
||||
|
||||
函数式编程利用方法作为执行任务的主要构造。创建一个方法,该方法接受一种数据,处理该数据,并输出新数据。将许多方法串在一起,您就拥有了一个动态且功能强大的应用程序。像 C 和 [Lua][2] 这样的编程语言就是这种编码风格的例子。
|
||||
|
||||
用代码完成任务的另一种方式是 Java 使用的面向对象模型。在面向对象编程中,方法是模板的组成部分。您可以创建对象,而不是将数据从一个方法发送到另一个方法,并可以通过使用它们的方法来更改它们。
|
||||
|
||||
从面向对象的角度来看,这是一个简单的 zombie apocalypse(僵尸末日)演示程序。在函数方法中,我使用一种方法生成数据,另一种方法使用该数据执行操作。面向对象的等价物是具有表示工作单元的类。这个示例应用程序向用户显示一条当天的消息,宣布这一天会有 zombie party(僵尸派对)或 zombie apocalypse。编写一个“day”对象,然后查询该对象以了解其特性是有意义的。作为演示面向对象构造的不同方面的借口,新的示例应用程序还将统计有多少僵尸出现在 party 上(或 apocalypse)。
|
||||
|
||||
Java 为每个类使用一个文件,因此要创建的第一个文件是“Day.Java”,它用作 Day 对象:
|
||||
|
||||
```
|
||||
package com.opensource.example;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
// 类
|
||||
public class Day {
|
||||
public static String weather;
|
||||
public int count;
|
||||
|
||||
// 构造方法
|
||||
public Day() {
|
||||
long myTime = System.currentTimeMillis();
|
||||
|
||||
if ( myTime%2 == 0 ) {
|
||||
weather = "paradise";
|
||||
} else {
|
||||
weather = "apocalypse";
|
||||
}
|
||||
}
|
||||
|
||||
// 方法
|
||||
public String report() {
|
||||
return weather;
|
||||
}
|
||||
|
||||
public int counter() {
|
||||
Random rand = new Random();
|
||||
count = count + rand.nextInt(100);
|
||||
|
||||
return(count);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
在“类”部分中,创建了两个域:“weather”和“count”。weather 是静态的。在一天的过程中(在这种假想的情况下),weather 不会改变。要么是 party,要么是 apocalypse,持续了一整天。然而,僵尸的数量在一天中会增加。
|
||||
|
||||
在“构造方法”部分,确定当天的天气。它是作为一个 [构造方法][3] 完成的,因为它只在类最初被调用时发生一次。
|
||||
|
||||
在“方法”部分,“report”方法只返回由构造方法确定和设置的天气报告。然而,“counter”方法生成一个随机数,并将其添加到当前僵尸计数中。
|
||||
|
||||
换句话说,这个类做了三件不同的事情:
|
||||
|
||||
- 表示应用程序定义的“day”。
|
||||
- 设置当天不变的天气报告。
|
||||
- 设置一天中不断增加的僵尸数量。
|
||||
|
||||
要使用这所有,请创建第二个文件:
|
||||
|
||||
```
|
||||
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());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
因为现在有两个文件,所以使用 Java IDE 运行代码是最简单的,但是如果不想使用 IDE,可以创建自己的 [JAR 文件][4]。运行代码以查看结果:
|
||||
|
||||
```
|
||||
Welcome to a zombie apocalypse
|
||||
Welcome to a zombie apocalypse
|
||||
There are 35 zombies out today.
|
||||
UPDATE: 67 zombies. UPDATE: 149 zombies.
|
||||
```
|
||||
|
||||
无论调用“report”方法多少次,“weather”都保持不变,但调用“counter”方法的次数越多,僵尸的数量就会增加。
|
||||
|
||||
### Java 方法
|
||||
|
||||
方法(或函数)是编程中的重要组成。在 Java 中,您可以将它们作为函数式编程的单个类的一部分使用,也可以在面向对象编程的类之间使用它们。两种类型的编程对于解决同一个问题有不同的视角,因此没有对与错之分。通过反复尝试,积累一点经验,你会知道哪一个最适合某个特定的问题。
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/23/1/java-methods
|
||||
|
||||
作者:[Seth Kenlon][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[ZhangZhanhaoxiang](https://github.com/ZhangZhanhaoxiang)
|
||||
校对:[校对者 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
|
||||
|
Loading…
Reference in New Issue
Block a user