Java 简明教程
Java - Methods
Java Methods
Java method 是一个语句集合,将其组合在一起来执行一个操作。例如,当您调用 System.out.println() 方法时,系统实际上执行多个语句来在控制台上显示一条消息。
A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console.
在本教程中,我们将学习如何创建有或没有返回值自己的方法,调用有或没有参数的方法,以及在程序设计中应用方法抽象。
In this tutorial, we will learn how to create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program design.
Creating a Java Method
若要创建 Java 方法,应该有 access modifier,后面是返回类型、方法的名称和参数列表。
To create a Java method, there should be an access modifier followed by the return type, method’s name, and parameters list.
Syntax to Create a Java Method
考虑以下示例来解释一个方法的语法 −
Considering the following example to explain the syntax of a method −
modifier returnType nameOfMethod (Parameter List) {
// method body
}
上面显示的语法包括:
The syntax shown above includes −
-
modifier − It defines the access type of the method and it is optional to use.
-
returnType − Method may return a value.
-
nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.
-
Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.
-
method body − The method body defines what the method does with the statements.
Example to Create a Java Method
以下是名为 minFunction() 的上述定义方法的源代码。此方法采用两个参数 n1 和 n2,并返回两者的最小值 −
Here is the source code of the above defined method called minFunction(). This method takes two parameters n1 and n2 and returns the minimum between the two −
/** the snippet returns the minimum between two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
Calling a Java Method
要使用一个方法,应该调用它。有两种方式可以调用一个方法:方法返回一个值或不返回任何值(没有返回值)。
For using a method, it should be called. There are two ways in which a method is called i.e., method returns a value or returning nothing (no return value).
方法调用的过程很简单。当一个程序调用一个方法时,程序控制将转移到被调用的方法。这个被调用的方法然后在两个条件下将控制返回给调用者,当 −
The process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method. This called method then returns control to the caller in two conditions, when −
-
the return statement is executed.
-
it reaches the method ending closing brace.
返回 void 的方法被视为调用语句。我们考虑一个示例−
The methods returning void is considered as call to a statement. Lets consider an example −
System.out.println("This is tutorialspoint.com!");
返回值的方法可以由以下示例理解−
The method returning value can be understood by the following example −
int result = sum(6, 9);
Example: Defining and Calling a Java Method
以下是如何定义一个方法以及如何调用它的示例−
Following is the example to demonstrate how to define a method and how to call it −
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
/** returns the minimum of two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
Minimum value = 6
The void Keyword with Java Methods
void 关键字允许我们创建不返回值的方法。在这里,在以下示例中,我们考虑了一个 void 方法 methodRankPoints。这个方法是一个 void 方法,不返回任何值。对 void 方法的调用必须是一个语句,即 methodRankPoints(255.7);。这是一个 Java 语句,以分号结尾,如下例所示。
The void keyword allows us to create methods which do not return a value. Here, in the following example we’re considering a void method methodRankPoints. This method is a void method, which does not return any value. Call to a void method must be a statement i.e. methodRankPoints(255.7);. It is a Java statement which ends with a semicolon as shown in the following example.
Example: Use of void keyword with Methods
public class ExampleVoid {
public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
System.out.println("Rank:A1");
}else if (points >= 122.4) {
System.out.println("Rank:A2");
}else {
System.out.println("Rank:A3");
}
}
}
Rank:A1
Passing Parameters by Value in Java Methods
在调用过程中,要传递参数。这些应该与方法规范中它们各自的参数处于相同的顺序。参数可以通过值或引用传递。
While working under calling process, arguments is to be passed. These should be in the same order as their respective parameters in the method specification. Parameters can be passed by value or by reference.
按值传递参数表示用一个参数调用一个方法。通过这种方式,参数值传递给参数。
Passing Parameters by Value means calling a method with a parameter. Through this, the argument value is passed to the parameter.
Example: Passing Parameters by Value
以下程序显示了一个按值传递参数的示例。即使在方法调用后,参数的值仍然保持不变。
The following program shows an example of passing parameter by value. The values of the arguments remains the same even after the method invocation.
public class swappingExample {
public static void main(String[] args) {
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45
Java Methods Overloading
当一个类有两个或更多具有相同名称但不同参数的方法时,它被称为方法重载。它不同于重写。在重写中,一个方法具有相同的方法名、类型、参数数量等。
When a class has two or more methods by the same name but different parameters, it is known as method overloading. It is different from overriding. In overriding, a method has the same method name, type, number of parameters, etc.
我们考虑前面讨论的用于查找最小整数类型数字的示例。如果我们希望找到最小双精度类型数字。然后将引入重载的概念来创建两个或更多具有相同名称但不同参数的方法。
Let’s consider the example discussed earlier for finding minimum numbers of integer type. If, let’s say we want to find the minimum number of double type. Then the concept of overloading will be introduced to create two or more methods with the same name but different parameters.
以下示例对此进行了说明−
The following example explains the same −
Example: Methods Overloading in Java
public class ExampleOverloading {
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
Minimum Value = 6
Minimum Value = 7.3
方法重载使程序可读。此处,两个方法具有相同的名称,但具有不同的参数。整型和双精度类型中的最小数字是结果。
Overloading methods makes program readable. Here, two methods are given by the same name but with different parameters. The minimum number from integer and double types is the result.
Using Command-Line Arguments
有时,在运行程序时,您将需要向程序传递一些信息。这可以通过将命令行参数传递给 main( ) 来实现。
Sometimes you will want to pass some information into a program when you run it. This is accomplished by passing command-line arguments to main( ).
当执行程序时,紧跟程序名称后的信息就是命令行参数。在 Java 程序中访问命令行参数非常容易。它们被存储为传递给 main( ) 的 String 数组中的字符串。
A command-line argument is the information that directly follows the program’s name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ).
Example
以下程序显示了它被调用的所有命令行参数 -
The following program displays all of the command-line arguments that it is called with −
public class CommandLine {
public static void main(String args[]) {
for(int i = 0; i<args.length; i++) {
System.out.println("args[" + i + "]: " + args[i]);
}
}
}
尝试按如下所示执行此程序 -
Try executing this program as shown here −
$java CommandLine this is a command line 200 -100
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
The this Keyword inside Java Methods
this 是 Java 中的关键字,用作对当前类对象(带有一个实例方法或 constructor)的引用。使用此关键字,您可以引用类的成员(例如构造函数、 variables 和 methods)。
this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.
Note− 关键字 this 只用在实例方法或构造函数内
Note − The keyword this is used only within instance methods or constructors
一般来说,关键字 this 用于 −
In general, the keyword this is used to −
-
Differentiate the instance variables from local variables if they have same names, within a constructor or a method.
class Student {
int age;
Student(int age) {
this.age = age;
}
}
-
Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.
class Student {
int age
Student() {
this(20);
}
Student(int age) {
this.age = age;
}
}
Example: Use of this keyword in Java Methods
以下是一个使用此关键字访问类成员的示例。将以下程序复制并粘贴到名为 This_Example.java 的文件中。
Here is an example that uses this keyword to access the members of a class. Copy and paste the following program in a file with the name, This_Example.java.
public class This_Example {
// Instance variable num
int num = 10;
This_Example() {
System.out.println("This is an example program on keyword this");
}
This_Example(int num) {
// Invoking the default constructor
this();
// Assigning the local variable <i>num</i> to the instance variable <i>num</i>
this.num = num;
}
public void greet() {
System.out.println("Hi Welcome to Tutorialspoint");
}
public void print() {
// Local variable num
int num = 20;
// Printing the local variable
System.out.println("value of local variable num is : "+num);
// Printing the instance variable
System.out.println("value of instance variable num is : "+this.num);
// Invoking the greet method of a class
this.greet();
}
public static void main(String[] args) {
// Instantiating the class
This_Example obj1 = new This_Example();
// Invoking the print method
obj1.print();
// Passing a new value to the num variable through parametrized constructor
This_Example obj2 = new This_Example(30);
// Invoking the print method again
obj2.print();
}
}
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint
Java Methods Variables Arguments (var-args)
JDK 1.5 允许您向方法传递可变数量的同类型参数。方法中的参数声明如下 -
JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows −
typeName... parameterName
在方法声明中,您指定类型,后跟省略号 (…)。一个方法中只能指定一个可变长度参数,该参数必须是最后一个参数。任何常规参数都必须在它之前。
In the method declaration, you specify the type followed by an ellipsis (…). Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it.
Example: Use of Variables Arguments (var-args)
public class VarargsDemo {
public static void main(String args[]) {
// Call method with variable args
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3});
}
public static void printMax( double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}
double result = numbers[0];
for (int i = 1; i < numbers.length; i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is " + result);
}
}
The max value is 56.5
The max value is 3.0
The finalize( ) Method
可以定义一种方法,在垃圾收集器对某个对象进行最终销毁之前,将会调用该方法。此方法称为 finalize( ),可用于确保对象干净地终止。
It is possible to define a method that will be called just before an object’s final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.
例如,您可以使用 finalize( ) 确保由该对象拥有的打开文件已关闭。
For example, you might use finalize( ) to make sure that an open file owned by that object is closed.
要为类添加一个终结器,只需定义 finalize( ) 方法。每当 Java 运行时准备回收该类的对象时,就会调用该方法。
To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that method whenever it is about to recycle an object of that class.
在 finalize( ) 方法中,您将指定在销毁对象之前必须执行的操作。
Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.
finalize( ) 方法具有以下常规形式 −
The finalize( ) method has this general form −
protected void finalize( ) {
// finalization code here
}
此处,关键字 protected 是一个说明符,该说明符阻止定义在其类外部的代码访问 finalize( )。
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.
这意味着你无法知道finalize()何时或是否会被执行。例如,如果你的程序在垃圾收集发生之前结束,则finalize()将不会执行。
This means that you cannot know when or even if finalize( ) will be executed. For example, if your program ends before garbage collection occurs, finalize( ) will not execute.