1. Introduction
1.绪论
In Java, methods are where we define the business logic of an application. They define the interactions among the data enclosed in an object.
在Java中,方法是我们定义应用程序的业务逻辑的地方。它们定义了对象中所包含的数据之间的相互作用。
In this tutorial, we’ll go through the syntax of Java methods, the definition of the method signature, and how to call and overload methods.
在本教程中,我们将了解Java方法的语法、方法签名的定义,以及如何调用和重载方法。
2. Method Syntax
2.方法的语法
First, a method consists of six parts:
首先,一个方法由六个部分组成。
- Access modifier: optionally we can specify from wherein the code one can access the method
- Return type: the type of the value returned by the method, if any
- Method identifier: the name we give to the method
- Parameter list: an optional comma-separated list of inputs for the method
- Exception list: an optional list of exceptions the method can throw
- Body: definition of the logic (can be empty)
Let’s see an example:
让我们看一个例子。
Let’s take a closer look at each of these six parts of a Java method.
让我们仔细看看Java方法的这六个部分。
2.1. Access Modifier
2.1.访问修改器
The access modifier allows us to specify which objects can have access to the method. There are four possible access modifiers: public, protected, private, and default (also called package-private).
access modifier允许我们指定哪些对象可以访问该方法。有四种可能的访问修改器。public、protected、private和default(也叫package-private)。
A method can also include the static keyword before or after the access modifier. This means that the method belongs to the class and not to the instances, and therefore, we can call the method without creating an instance of the class. Methods without the static keyword are known as instance methods and may only be invoked on an instance of the class.
一个方法也可以在访问修饰符之前或之后包含static关键字。这意味着该方法属于类,而不是属于实例,因此,我们可以在不创建类的实例的情况下调用该方法。没有static关键字的方法被称为实例方法,只能在该类的实例上调用。
Regarding performance, a static method will be loaded into memory just once – during class loading – and are thus more memory-efficient.
在性能方面,静态方法只被加载到内存中一次–在类的加载过程中–因此更加节省内存。
2.2. Return Type
2.2.返回类型
Methods can return data to the code where they have been called from. A method can return a primitive value or an object reference, or it can return nothing if we use the void keyword as the return type.
方法可以向其被调用的代码返回数据。一个方法可以返回一个原始值或一个对象引用,如果我们使用void关键字作为返回类型,它也可以什么都不返回。
Let’s see an example of a void method:
让我们看看一个void方法的例子。
public void printFullName(String firstName, String lastName) {
System.out.println(firstName + " " + lastName);
}
If we declare a return type, then we have to specify a return statement in the method body. Once the return statement has been executed, the execution of the method body will be finished and if there are more statements, these won’t be processed.
如果我们声明了一个返回类型,那么我们必须在方法体中指定一个return语句。一旦return语句被执行,方法体的执行就会结束,如果还有更多的语句,这些就不会被处理。
On the other hand, a void method doesn’t return any value and, thus, does not have a return statement.
另一方面,void方法不返回任何值,因此,没有return语句。
2.3. Method Identifier
2.3.方法标识符
The method identifier is the name we assign to a method specification. It is a good practice to use an informative and descriptive name. It’s worth mentioning that a method identifier can have at most 65536 characters (a long name though).
方法标识符是我们分配给一个方法规范的名称。使用一个信息量大、描述性强的名字是一个好的做法。值得一提的是,一个方法标识符最多可以有65536个字符(虽然是个长名字)。
2.4. Parameter List
2.4 参数列表
We can specify input values for a method in its parameter list, which is enclosed in parentheses. A method can have anywhere from 0 to 255 parameters that are delimited by commas. A parameter can be an object, a primitive or an enumeration. We can use Java annotations at the method parameter level (for example the Spring annotation @RequestParam).
我们可以在一个方法的参数列表中指定输入值,参数列表用小括号括起来。一个方法可以有0到255个参数,以逗号为界。一个参数可以是对象,基元或枚举。我们可以在方法参数级别使用Java注解(例如,Spring注解@RequestParam)。
2.5. Exception List
2.5.异常列表
We can specify which exceptions are thrown by a method by using the throws clause. In the case of a checked exception, either we must enclose the code in a try-catch clause or we must provide a throws clause in the method signature.
我们可以通过使用throws子句来指定一个方法会抛出哪些异常。如果是被检查的异常,我们必须将代码包围在一个try-catch子句中,或者我们必须在方法签名中提供一个throws子句。
So, let’s take a look at a more complex variant of our previous method, which throws a checked exception:
那么,让我们来看看我们之前的方法的一个更复杂的变体,它抛出一个检查过的异常。
public void writeName(String name) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
out.println("Name: " + name);
out.close();
}
2.6. Method Body
2.6.方法主体
The last part of a Java method is the method body, which contains the logic we want to execute. In the method body, we can write as many lines of code as we want — or none at all in the case of static methods. If our method declares a return type, then the method body must contain a return statement.
Java方法的最后一部分是方法体,它包含了我们想要执行的逻辑。在方法体中,我们可以写任意多行的代码–或者在静态方法中完全不写。如果我们的方法声明了一个返回类型,那么方法体必须包含一个返回语句。
3. Method Signature
3.方法签名
As per its definition, a method signature is comprised of only two components — the method’s name and parameter list.
根据其定义,方法签名仅由两部分组成–方法的名称和参数列表。
So, let’s write a simple method:
所以,让我们写一个简单的方法。
public String getName(String firstName, String lastName) {
return firstName + " " + middleName + " " + lastName;
}
The signature of this method is getName(String firstName, String lastName).
这个方法的签名是getName(String firstName, String lastName)。
The method identifier can be any identifier. However, if we follow common Java coding conventions, the method identifier should be a verb in lowercase that can be followed by adjectives and/or nouns.
方法标识符可以是任何标识符。然而,如果我们遵循常见的Java编码惯例,方法标识符应该是一个小写的动词,后面可以接形容词和/或名词。
4. Calling a Method
4.调用一个方法
Now, let’s explore how to call a method in Java. Following the previous example, let’s suppose that those methods are enclosed in a Java class called PersonName:
现在,让我们来探讨一下如何在Java中调用一个方法。按照前面的例子,我们假设这些方法被封闭在一个叫做PersonName的Java类中。
public class PersonName {
public String getName(String firstName, String lastName) {
return firstName + " " + middleName + " " + lastName;
}
}
Since our getName method is an instance method and not a static method, in order to call the method getName, we need to create an instance of the class PersonName:
由于我们的getName方法是一个实例方法而不是静态方法,为了调用getName方法,我们需要创建一个PersonName类的实例。
PersonName personName = new PersonName();
String fullName = personName.getName("Alan", "Turing");
As we can see, we use the created object to call the getName method.
我们可以看到,我们使用创建的对象来调用getName方法。
Finally, let’s take a look at how to call a static method. In the case of a static method, we don’t need a class instance to make the call. Instead, we invoke the method with its name prefixed by the class name.
最后,让我们来看看如何调用static方法。在静态方法的情况下,我们不需要一个类实例来进行调用。相反,我们在调用该方法时,在其名称前加上类的名称。
Let’s demonstrate using a variant of the previous example:
让我们用前面例子的一个变体来演示。
public class PersonName {
public static String getName(String firstName, String lastName) {
return firstName + " " + middleName + " " + lastName;
}
}
In this case, the method call is:
在这种情况下,方法的调用是。
String fullName = PersonName.getName("Alan", "Turing");
5. Method Overloading
5.方法重载
Java allows us to have two or more methods with the same identifier but different parameter list — different method signatures. In this case, we say that the method is overloaded. Let’s go with an example:
Java允许我们有两个或多个具有相同标识符但参数列表不同的方法–不同的方法签名。在这种情况下,我们说该方法是重载的。让我们举个例子。
public String getName(String firstName, String lastName) {
return getName(firstName, "", lastName);
}
public String getName(String firstName, String middleName, String lastName) {
if (!middleName.isEqualsTo("")) {
return firstName + " " + lastName;
}
return firstName + " " + middleName + " " + lastName;
}
Method overloading is useful for cases like the one in the example, where we can have a method implementing a simplified version of the same functionality.
方法重载对于像例子中的情况很有用,我们可以有一个方法实现相同功能的简化版本。
Finally, a good design habit is to ensure that overloaded methods behave in a similar manner. Otherwise, the code will be confusing if a method with the same identifier behaves in a different way.
最后,一个好的设计习惯是确保重载方法的行为方式相似。否则,如果具有相同标识符的方法的行为方式不同,代码就会变得混乱。
6. Conclusion
6.结语
In this tutorial, we’ve explored the parts of Java syntax involved when specifying a method in Java.
在本教程中,我们已经探讨了在Java中指定方法时涉及的部分Java语法。
In particular, we went through the access modifier, the return type, the method identifier, the parameter list, the exception list, and the method body. Then we saw the definition of the method signature, how to call a method, and how to overload a method.
特别是,我们浏览了访问修饰符、返回类型、方法标识符、参数列表、异常列表和方法体。然后我们看到了方法签名的定义,如何调用一个方法,以及如何重载一个方法。
As usual, the code seen here is available over on GitHub.
像往常一样,这里看到的代码可以在GitHub上找到,。