Java方法


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

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

创建方法


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

语法

public static int methodName(int a, int b) {
    //方法体
}
  • public static:修饰符

  • int:返回类型

  • methodName:方法名称

  • a, b:形式参数

  • int a, int b:参数清单

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

语法

modifier returnType nameOfMethod (Parameter List) {
    //方法体
}

上面显示的语法包括:

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

  • 返回类型:方法可能会返回一个值。

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

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

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

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

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

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 newbiego.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关键字使我们可以创建不返回值的方法。在下面的示例中,我们考虑使用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);

        //调用swap方法
        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);
    }

    //整数
    public static int minFunction(int n1, int n2) {
        int min;
        if (n1 > n2)
            min = n2;
        else
            min = n1;

        return min;
    }
   
    //对于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关键字


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

注意:关键字 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 newbiego");
    }
      
    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();
      
        //调用print方法
        obj1.print();
	  
        //通过参数化的构造函数将新值传递给num变量
        This_Example obj2 = new This_Example(30);
      
        //再次调用print方法
        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 newbiego
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 newbiego

可变参数(var-args)


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

typeName... parameterName

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

public class VarargsDemo {

    public static void main(String args[]) {
        //带有变量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( ) {
    //此处的完成代码
}

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

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