目录

Java - Methods

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

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

创建方法

考虑以下示例来解释方法的语法 -

Syntax

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

这里,

  • public static - modifier

  • int - 返回类型

  • methodName - 方法的名称

  • a, b - 形式参数

  • int a, int b - 参数列表

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

Syntax

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

上面显示的语法包括 -

  • modifier - 它定义方法的访问类型,并且可以使用它。

  • returnType - Method可以返回一个值。

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

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

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

Example

以下是上面定义的方法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 iowiki.com!");

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

int result = sum(6, 9);

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

Example

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

这将产生以下结果 -

Output

Minimum value = 6

无效关键字

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

Example

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");
      }
   }
}

这将产生以下结果 -

Output

Rank:A1

按值传递参数

在调用进程下工作时,将传递参数。 它们的顺序应与方法规范中各自的参数顺序相同。 参数可以通过值或引用传递。

通过Value传递参数意味着使用参数调用方法。 通过这个,参数值被传递给参数。

Example

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

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);
   }
}

这将产生以下结果 -

Output

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类型。 然后将引入重载的概念以创建具有相同名称但不同参数的两个或更多方法。

以下示例解释相同 -

Example

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

这将产生以下结果 -

Output

Minimum Value = 6
Minimum Value = 7.3

重载方法使程序可读。 这里,两个方法由相同的名称给出,但具有不同的参数。 结果是整数和双精度的最小数。

Using Command-Line Arguments

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

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

Example

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

public class CommandLine {
   public static void main(String args[]) { 
      for(int i = 0; i<args.length; i++) {
         System.out.println("args[" + i + "]: " +  args[i]);
      }
   }
}

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

$java CommandLine this is a command line 200 -100

这将产生以下结果 -

Output

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

这个关键字

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

Note - 关键字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;	
   }
}

Example

以下是使用this关键字访问类成员的示例。 将以下程序复制并粘贴到名为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 IoWiki");
   }
   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(); 
   }
}

这将产生以下结果 -

Output

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 IoWiki
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 IoWiki

Variable Arguments(var-args)

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

typeName... parameterName

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

Example

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);
   }
}

这将产生以下结果 -

Output

The max value is 56.5
The max value is 3.0

The finalize( ) Method

可以定义一个方法,该方法将在垃圾收集器最终销毁对象之前调用。 此方法称为finalize( ) ,它可用于确保对象完全终止。

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

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

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

finalize()方法有这种一般形式 -

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

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

这意味着您无法知道何时甚至是否将执行finalize()。 例如,如果程序在垃圾收集发生之前结束,则finalize()将不会执行。

↑回到顶部↑
WIKI教程 @2018