橘子味的心
标题:Java方法

Java中的方法是一组语句,它们组合在一起以执行各种操作。 例如,当调用System.out.println()方法时,系统实际上会执行多个语句,以便在控制台上显示消息。

下面将学习如何使用或不使用返回值创建自己的方法,使用或不使用参数调用方法,以及在程序设计中应用方法抽象。

1. 创建方法

下面来看看方法的语法 -

  1. public static int methodName(int a, int b) {
  2. // body
  3. }
  4. Java

在上面语法中,

  • public static − 修辞符
  • int − 返回值的类型
  • methodName − 方法的名称
  • a, b − 形式参数
  • int a, int b − 参数列表

方法定义由方法头和方法体组成。以下语法中显示了相同的内容 -

  1. modifier returnType nameOfMethod (Parameter List) {
  2. // method body
  3. }
  4. Java

上面显示的语法包括 -

  • modifier - 它定义方法的访问类型,它可能是:public,private,protected或不指定。
  • returnType - 方法可以返回一个值。
  • nameOfMethod - 这是方法名称,方法签名由方法名称和参数列表组成。
  • Parameter List - 参数列表,它是方法的类型,顺序和参数数量。 这些是可选的,方法可能包含零参数。
  • method body - 方法体定义方法对语句的作用。

示例

以下代码中定义了min()方法。 这个方法有两个int类型的参数:num1num2,并返回两者之间的最大值 -

  1. /** 返回两个数字之间的最小值 */
  2. public static int minFunction(int n1, int n2) {
  3. int min;
  4. if (n1 > n2)
  5. min = n2;
  6. else
  7. min = n1;
  8.  
  9. return min;
  10. }
  11. Java

2. 方法调用

可通过调用方法来使用方法,调用方法有两种方式,即方法有返回值或无返回任何值。

方法调用的过程很简单。 当程序调用方法时,程序控制将转移到被调用的方法。 这个被调用的方法然后在两个条件下将控制权返回给调用者,即 -

  • return语句被执行。
  • 它到达方法的结束,即右大括号(})。

对返回void的方法的调用 -

  1. System.out.println("This is Yiibai.com!");
  2. Java

对有返回值的方法的调用 -

  1. int result = sum(6, 9);
  2. Java

以下是演示如何定义方法以及如何调用方法的示例 -

  1. public class ExampleMinNumber {
  2.  
  3. public static void main(String[] args) {
  4. int a = 111;
  5. int b = 125;
  6. int c = getMin(a, b);
  7. System.out.println("最小值 = " + c);
  8. }
  9.  
  10. /** 返回两个 int 数值的最小值 */
  11. public static int getMin(int n1, int n2) {
  12. int min;
  13. if (n1 > n2)
  14. min = n2;
  15. else
  16. min = n1;
  17.  
  18. return min;
  19. }
  20. }
  21. Java

执行上面示例代码,得到以下结果:

  1. 最小值 = 111
  2. Shell

3. void关键字

void关键字允许创建不返回值的方法。在下面的例子中有一个返回值是void的方法methodRankPoints,它不返回任何值。 调用void方法必须是一个语句,即methodRankPoints(245.67);. 它是一个以分号结尾的Java语句,如以下示例所示 -

  1. public class ExampleVoid {
  2.  
  3. public static void main(String[] args) {
  4. methodRankPoints(245.67);
  5. }
  6.  
  7. public static void methodRankPoints(double points) {
  8. if (points >= 202.5) {
  9. System.out.println("Rank:A1");
  10. }else if (points >= 122.4) {
  11. System.out.println("Rank:A2");
  12. }else {
  13. System.out.println("Rank:A3");
  14. }
  15. }
  16. }
  17. Java

执行上面示例代码,得到以下结果:

4. 按值传递参数

在按值传递参数时需要传递参数。它们的顺序应与方法规范中的参数顺序相同。参数可以通过值或引用传递。

通过值传递参数是使用参数调用方法。 通过这样将参数值将传递给参数。

示例

以下程序显示了按值传递参数的示例。 即使在方法调用之后,参数的值仍保持不变。

  1. public class swappingExample {
  2.  
  3. public static void main(String[] args) {
  4. int a = 30;
  5. int b = 45;
  6. System.out.println("Before swapping, a = " + a + " and b = " + b);
  7.  
  8. // 调用交换方法
  9. swapFunction(a, b);
  10. System.out.println("Now, Before and After swapping values will be same here:");
  11. System.out.println("After swapping, a = " + a + " and b is " + b);
  12. }
  13.  
  14. public static void swapFunction(int a, int b) {
  15. System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
  16. // 交换 n1 和 n2
  17. int c = a;
  18. a = b;
  19. b = c;
  20. System.out.println("After swapping(Inside), a = " + a + " b = " + b);
  21. }
  22. }
  23. Java

执行上面示例代码,得到以下结果:

  1. Before swapping, a = 30 and b = 45
  2. Before swapping(Inside), a = 30 b = 45
  3. After swapping(Inside), a = 45 b = 30
  4. Now, Before and After swapping values will be same here:
  5. After swapping, a = 30 and b is 45
  6. Shell

5. 方法重载

当一个类有两个或多个同名但方法不同参数的方法时,称为方法重载。 它与重写不同。 在重写中,方法具有相同的方法名称,类型,参数数量等。

在前面讨论的用于查找最小整数类型数的示例中,假设想要查找两个double类型的最小数值。 可引入重载的概念以创建具有相同名称但不同参数的两个或更多方法。

参考以下示例代码 -

  1. public class ExampleOverloading {
  2.  
  3. public static void main(String[] args) {
  4. int a = 11;
  5. int b = 6;
  6. double c = 7.3;
  7. double d = 9.4;
  8. int result1 = getMin(a, b);
  9.  
  10. // 具有相同函数名称,但数字不同参数
  11. double result2 = getMin(c, d);
  12. System.out.println("Minimum Value = " + result1);
  13. System.out.println("Minimum Value = " + result2);
  14. }
  15.  
  16. // 处理 int 类型的数值(方法重载)
  17. public static int getMin(int n1, int n2) {
  18. int min;
  19. if (n1 > n2)
  20. min = n2;
  21. else
  22. min = n1;
  23.  
  24. return min;
  25. }
  26.  
  27. // 处理 double 类型的数值(方法重载)
  28. public static double getMin(double n1, double n2) {
  29. double min;
  30. if (n1 > n2)
  31. min = n2;
  32. else
  33. min = n1;
  34.  
  35. return min;
  36. }
  37. }
  38. Java

执行上面示例代码,得到以下结果:

  1. Minimum Value = 6
  2. Minimum Value = 7.3
  3. Shell

重载方法使程序可读。这里,两个方法由相同的名称给出但具有不同的参数类型。结果是求int类型和double类型的最小数。

6. 使用命令行参数

有时希望在运行程序时将一些信息传递给程序。它是通过将命令行参数传递给main()来实现的。

命令行参数是执行时在命令行上直接跟随程序名称的信息。 要访问Java程序中的命令行参数非常简单。 它们作为字符串存储在传递给main()String类型数组中。

示例

以下程序显示传递给程序的所有命令行参数 -

  1. public class CommandLine {
  2.  
  3. public static void main(String args[]) {
  4. for(int i = 0; i<args.length; i++) {
  5. System.out.println("args[" + i + "]: " + args[i]);
  6. }
  7. }
  8. }
  9. Java

使用以下方式执行此程序 -

  1. C:/> java CommandLine this is a command line 200 -100
  2. Shell

那么将得到以下结果:

  1. args[0]: this
  2. args[1]: is
  3. args[2]: a
  4. args[3]: command
  5. args[4]: line
  6. args[5]: 200
  7. args[6]: -100
  8. Shell

7. this 关键字

this是Java中的一个关键字,用作对当前类对象的引用,在实例方法或构造函数中。 使用它可以引用类的成员,例如:构造函数,变量和方法。

注 - this关键字仅在实例方法或构造函数中使用。

通常,this关键字用于 -

  • 如果实例变量在构造函数或方法中具有相同的名称,则将它们与局部变量区分开来。

    1. class Student {
    2. private int age;
    3. Student(int age) {
    4. this.age = age;
    5. }
    6. }
    7. Java
  • 从类中的其他方法调用一种类型的构造函数(参数化构造函数或默认值),称为显式构造函数调用。

    1. class Student {
    2. int age
    3. Student() {
    4. this(20);
    5. }
    6.  
    7. Student(int age) {
    8. this.age = age;
    9. }
    10. }
    11. Java

以下是使用this关键字访问类成员的示例 -

  1. public class ThisExample {
  2. // 实例变量:num
  3. int num = 10;
  4. ThisExample() {
  5. System.out.println("This is an example program on keyword this");
  6. }
  7.  
  8. ThisExample(int num) {
  9. // 调用默认构造方法
  10. this();
  11.  
  12. // 将局部变量 num 分配给实例变量 num
  13. this.num = num;
  14. }
  15.  
  16. public void greet() {
  17. System.out.println("Hi Welcome to Yiibai");
  18. }
  19.  
  20. public void print() {
  21. // 局部变量:num
  22. int num = 20;
  23.  
  24. // 打印局部变量
  25. System.out.println("value of local variable num is : "+num);
  26.  
  27. // 打印实例变量
  28. System.out.println("value of instance variable num is : "+this.num);
  29.  
  30. // 调用类方法
  31. this.greet();
  32. }
  33.  
  34. public static void main(String[] args) {
  35. // 实例化该类
  36. ThisExample obj1 = new ThisExample();
  37.  
  38. // 调用 print 方法
  39. obj1.print();
  40.  
  41. //通过参数化构造函数将新值传递给 num 变量
  42. ThisExample obj2 = new ThisExample(30);
  43.  
  44. // 再次调用 print 方法
  45. obj2.print();
  46. }
  47. }
  48. Java

执行上面示例代码,得到以下结果 -

  1. This is an example program on keyword this
  2. value of local variable num is : 20
  3. value of instance variable num is : 10
  4. Hi Welcome to Yiibai
  5. This is an example program on keyword this
  6. value of local variable num is : 20
  7. value of instance variable num is : 30
  8. Hi Welcome to Yiibai
  9. Shell

8. 变量参数(var-args)

JDK 1.5允许将可变数量的相同类型的参数传递给方法。方法中的参数声明如下 -

  1. typeName... parameterName
  2. Java

在方法声明中,指定类型后跟省略号(...)。 在方法中只能指定一个可变长度参数,并且此参数必须是最后一个参数。

  1. public class VarargsDemo {
  2.  
  3. public static void main(String args[]) {
  4. // 使用变量参数调用方法
  5. printMax(314, 321, 213, 212, 356.5);
  6. printMax(new double[]{1, 2, 3});
  7. }
  8.  
  9. public static void printMax( double... numbers) {
  10. if (numbers.length == 0) {
  11. System.out.println("No argument passed");
  12. return;
  13. }
  14.  
  15. double result = numbers[0];
  16.  
  17. for (int i = 1; i < numbers.length; i++)
  18. if (numbers[i] > result)
  19. result = numbers[i];
  20. System.out.println("参数列表中的最大值是:" + result);
  21. }
  22. }
  23. Java

执行上面示例代码,得到以下结果 -

  1. 参数列表中的最大值是:356.5
  2. 参数列表中的最大值是:3.0
  3. Shell

9. finalize()方法

finalize()方法在垃圾收集器对象最终销毁之前调用,它可用于确保对象完全终止。例如,可以使用finalize()来确保该对象拥有的打开文件已关闭。

要将终结器添加到类中,只需定义finalize()方法即可。只要Java方法要回收该类的对象,它就会调用该方法。

finalize()方法中,将指定在销毁对象之前必须执行的操作。finalize()方法有这种一般形式 -

  1. protected void finalize( ) {
  2. // finalization code here
  3. }
  4. Java

这里,关键字protected是一个修辞符,它阻止通过类外部定义的代码访问finalize()
我们无法知道Java何时或甚至是否将执行finalize()方法。如果程序在垃圾收集发生之前结束,则finalize()将不会执行。