文章目录
前言
Java中的方法是语句的集合,使用这些语句完成特定的功能操作。例如,当我们调用System.out.println()方法时,系统实际上执行了多个语句来将消息输出到console控制台上。
这一节,我们将会学习如何创建带返回值和不带返回值的方法,带参和不带参调用方法,并在程序设计中应用抽象方法。
创建方法
我们通过下面代码实例来学习创建方法的语法。
public static int methodName(int a, int b) {
//方法体
}
在上面代码中:
- public static - 修饰器
- int - 返回类型
- methodName - 方法的名称
- a和b - 形式参数
- int a, int b - 参数清单
方法的定义包含方法头和方法体两部分,其定义的描述形式可以这样来表述:
modifier returnType nameOfMethod (Parameter List) {
//方法体
}
上面语法形式中包含:
- modifier - 它定义了方法的访问类型,并且是可选的。
- returnType - 方法可能返回值的类型
- nameOfMethod - 方法的名称
- Parameter List - 参数清单,包含参数类型、参数名和参数的顺序。参数是可选的,方法可以没有参数。
- method body - 方法体,包含了方法中的执行语句,确定了方法做了哪些事情。
程序实例
下面定义的是minFunction()方法,其包含两个参数n1和n2,返回的是这两个参数中最小的值。
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);
}
/** 返回两个数字中较小的一个 */
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)。
程序实例
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);
// 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
方法的重载
当一个类里有多个同名但参数数目不同的方法,就意味着方法有重载。重载和覆写不同,在覆写时,方法的名称、返回类型和参数都是保持一样。
我们来考虑一下前面提到的计算int整型最小数的那个方法。如果我们还想计算double类型的最小数的话,我们就可以通过声明一个同名但参数类型是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);
//调用相同的方法,传入不同的参数
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
//接受int类型数据
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
方法重载可以增强程序的可读性。在上述程序实例中,两个方法名字相同但参数不同,其各自返回的是int和double类型中最小值。
使用命令行参数
有时候我们需要在程序运行的时候输入参数,这可以通过传命令行参数给main()方法。
当使用java命令执行程序时,只需要把参数接在类名后面。程序中使用命令行参数也很简单,这些参数被保存在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命令执行程序时带上参数“this is a command line 200 -100”:
$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关键字来访问类的成员。
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();
//将局部变量赋值给实例变量
this.num = num;
}
public void greet() {
System.out.println("Hi Welcome to Tutorialspoint");
}
public void print() {
//局部变量num
int num = 20;
//打印局部变量num
System.out.println("value of local variable num is : "+num);
//打印实例变量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 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
可变参数
JDK 1.5之后引入了可变参数,也就是我们可以对一个方法传入相同类型的不同数量参数。参数在方法中的定义方式如下:
typeName... parameterName
在方法的声明中,我们使用省略号(…)来指定可变数量参数。一个方法中只能定义一个可变参数,并且这个可变参数必须放在所有参数的最后面。
程序实例
public class VarargsDemo {
public static void main(String args[]) {
//调用printMax()方法
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()方法里面定义对象销毁前需要执行的内容。finalize()方法有通用的声明格式:
protected void finalize( ) {
//在这里写销毁代码
}
在这里,protected关键字可以防止通过类外部定义的代码访问finalize()方法。
finalize()方法的性质意味着我们不知道其在何时执行,甚至不知道其执行或不执行。例如,如果程序在垃圾回收发生之前结束,finalize()方法将不会执行。
关注公众号「小白轻松学编程」
更多交流,欢迎微信搜索并关注公众号 「 小白轻松学编程 」!
博客里所有教程会第一时间在公众号上更新哟,扫码关注一下吧~