Java - 方法函数

Java - 方法函数 首页 / Java入门教程 / Java - 方法函数

Java方法是语句的集合,它们在一起执行一个函数。如当您调用System.out.println()方法时,系统实际上会执行几条语句,以便在控制台上显示消息。

创建方法

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

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

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

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

上面显示的语法包括-

  • modifier               - 修饰符它定义方法的访问类型,可以选择使用。

  • returType             - 方法可能会返回值。

  • nameOfMethod  - 这是方法名称。

  • Parameter List    - 参数列表,它是方法的类型、顺序和参数数量。

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

下面是上面定义的min()方法的源代码。此方法接受两个参数Num1和Num2,并返回两个之间的最大值

/** 该片段返回两个数字之间的最小值 */

public static int minFunction(int n1, int n2) {
   int min;
   if (n1 > n2)
      min = n2;
   else
      min = n1;
   return min; 
}

方法调用

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

System.out.println("This is learnfk.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);
   }

   /** 返回两个数字中的最小值 */
   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关键字使无涯教程可以创建不返回值的方法。

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

      //调用交换方法
      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);
      
      //用 n2 交换 n1
      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

方法重载

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

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);
      
      //相同的函数名不同的参数
      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<args.length; i++) {
         System.out.println("args[" + i + "]: " +  args[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

this关键字

这是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关键字访问类成员的示例。将以下程序复制并粘贴到名为this_Example.java的文件中。

public class This_Example {
   //实例变量 num
   int num = 10;
	
   This_Example() {
      System.out.println("This is an example program on keyword this");	
   }

   This_Example(int num) {
      //调用默认构造函数
      this();
      
      //将局部变量 num 分配给实例变量 num
      this.num = num;	   
   }
   
   public void greet() {
      System.out.println("Hi Welcome to Learnfk");
   }
      
   public void print() {
      //局部变量 num
      int num = 20;
      
      //打印局部变量
      System.out.println("value of local variable num is : "+num);
      
      //打印实例变量
      System.out.println("value of instance variable num is : "+this.num);
      
      //调用一个类的 greet 方法
      this.greet();     
   }
   
   public static void main(String[] args) {
      //实例化类
      This_Example obj1 = new This_Example();
      
      //调用打印方法
      obj1.print();
	  
      //通过参数化构造函数将新值传递给 num 变量
      This_Example obj2 = new This_Example(30);
      
      //再次调用打印方法
      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 Learnfk
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 Learnfk

可变参数

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

typeName... parameterName

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

public class VarargsDemo {

   public static void main(String 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()方法具有以下通用形式-

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

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

面试现场 -〔白海飞〕

深入拆解Tomcat & Jetty -〔李号双〕

Java性能调优实战 -〔刘超〕

浏览器工作原理与实践 -〔李兵〕

JavaScript核心原理解析 -〔周爱民〕

Selenium自动化测试实战 -〔郭宏志〕

容器实战高手课 -〔李程远〕

Python实战 · 从0到1搭建直播视频平台 -〔Barry〕

结构学习力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)