Java方法是一组语句,它们组合在一起以执行操作.例如,当您调用System.out. println()方法时,系统实际上会执行多个语句,以便在控制台上显示消息.
现在,您将学习如何使用或不使用返回值创建自己的方法,调用带或不带参数的方法,并在程序设计中应用方法抽象.
考虑以下示例来解释方法的语法 :
语法
public static int methodName(int a, int b) { // body }
这里,
public static : 修饰符
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 IT屋.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数组中.
示例
以下程序显示全部使用&minus调用它的命令行参数;
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
此是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 { // 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
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()方法即可. Java运行时只要回收该类的对象就会调用该方法.
在finalize()方法中,您将指定在销毁对象之前必须执行的操作. .
finalize()方法具有以下一般形式 :
protected void finalize( ) { // finalization code here }
这里,关键字protected是一个说明符,它阻止通过定义的代码访问finalize()在类之外.
这意味着您无法知道何时甚至是否将执行finalize().例如,如果程序在垃圾收集发生之前结束,则finalize()将不会执行.