📜  Java-方法

📅  最后修改于: 2020-12-21 01:41:52             🧑  作者: Mango


Java方法是语句的集合,这些语句组合在一起以执行操作。当您调用System.out时。例如,使用println()方法,系统实际上执行几个语句,以便在控制台上显示一条消息。

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

建立方法

考虑以下示例以说明方法的语法-

句法

public static int methodName(int a, int b) {
   // body
}

这里,

  • 公共静态-修饰符

  • int-返回类型

  • methodName-方法名称

  • a,b-形式参数

  • int a,int b-参数列表

方法定义由方法标题和方法主体组成。以下语法显示相同的内容-

句法

modifier returnType nameOfMethod (Parameter List) {
   // method body
}

上面显示的语法包括-

  • 修饰符-它定义方法的访问类型,并且是可选的。

  • returnType-方法可以返回一个值。

  • nameOfMethod-这是方法名称。方法签名由方法名称和参数列表组成。

  • 参数列表参数列表,它是方法的类型,顺序和参数数量。这些是可选的,方法可能包含零个参数。

  • 方法主体-方法主体定义方法对语句的作用。

这是上面定义的名为min()的方法的源代码。此方法采用两个参数num1和num2,并返回两个参数之间的最大值-

/** 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; 
}

方法调用

对于使用方法,应调用它。有两种方法被调用,即方法返回值或不返回任何值(无返回值)。

方法调用的过程很简单。当程序调用方法时,程序控件将转移到被调用的方法。然后,在以下两种情况下,此被调用方法将控制权返回给调用方:

  • return语句被执行。
  • 它到达结束括号的方法。

返回void的方法被视为对语句的调用。让我们考虑一个例子-

System.out.println("This is tutorialspoint.com!");

该方法的返回值可以通过以下示例理解-

int result = sum(6, 9);

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

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

无效关键字

void关键字使我们可以创建不返回值的方法。在下面的示例中,我们考虑一个void方法methodRankPoints 。此方法是void方法,它不返回任何值。调用void方法必须是一条语句,即methodRankPoints(255.7); 。这是一条以分号结尾的Java语句,如以下示例所示。

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

按值传递参数

在调用过程中工作时,必须传递参数。这些方法应与方法规范中其各自参数的顺序相同。参数可以按值或引用传递。

通过值传递参数意味着调用带有参数的方法。通过此操作,参数值将传递给参数。

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

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

方法重载

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

让我们考虑一下前面讨论的用于查找最小整数类型的示例。假设我们要查找double类型的最小数量。然后,将引入重载的概念来创建两个或更多个名称相同但参数不同的方法。

以下示例解释了相同的内容-

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

重载方法使程序可读。这里,两个方法的名称相同,但参数不同。结果是整数和双精度类型中的最小值。

使用命令行参数

有时,您会希望在运行程序时将一些信息传递给程序。这是通过将命令行参数传递给main()来完成的。

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

以下程序显示使用以下命令调用的所有命令行参数:

public class CommandLine {

   public static void main(String args[]) { 
      for(int i = 0; i

尝试执行此程序,如下所示-

$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

这个关键字

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

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

这个

通常,关键字this用于-

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

class Student {
   int age;   
   Student(int age) {
      this.age = age;    
   }
}
  • 从类的另一种构造函数中调用另一种构造函数(参数化的构造函数或默认构造函数)。这称为显式构造函数调用。

class Student {
   int age
   Student() {
      this(20);
   }
   
   Student(int age) {
      this.age = age;    
   }
}

这是一个使用关键字访问类成员的示例。将以下程序复制并粘贴到名称为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 num to the instance variable num
      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

可变参数(var-args)

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

typeName... parameterName

在方法声明中,指定类型,后跟省略号(…)。一个方法中只能指定一个可变长度参数,并且该参数必须是最后一个参数。任何常规参数都必须在其之前。

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

finalize()方法

可以定义一个将在垃圾回收器最终破坏对象之前调用的方法。此方法称为finalize() ,可用于确保对象干净终止。

例如,您可以使用finalize()确保该对象拥有的打开文件已关闭。

要将终结器添加到类中,只需定义finalize()方法即可。 Java运行时将在每次要回收该类的对象时调用该方法。

在finalize()方法中,您将指定在销毁对象之前必须执行的那些操作。

finalize()方法具有以下一般形式-

protected void finalize( ) {
   // finalization code here
}

在此,关键字protected是一个说明符,它防止通过其类外部定义的代码访问finalize()。

这意味着您不知道何时或什至将执行finalize()。例如,如果您的程序在垃圾回收发生之前结束,则finalize()将不会执行。