方法的声明和使用
方法就是一段可重复调用的代码段,
方法与函数的关系?
在有些书中把方法成为函数,其实两者是同样的概念,只是称呼方式不一样。
方法的定义格式:
public static 返回值类型 方法名称(类型 参数1,参数2,...) { //方法主体 程序语句; 【return表达式】; }
如果不需要船体参数到方法中,只要将括号写出,不必填入任何内容,此外,如果方法没有返回值,则在返回值类型处要明确写出void,此时,在方法中return语句可以省略,方法执行完后无论是否存在返回值都将返回到方法的调用处并向下继续执行。
命名规范:
在定义类的时候,全部单词的首字母必须大写,
在定义方法的时候,第一个单词的首字母小写,之后每个单词的首字母大写如:printInfo()
下面看一个有返回值类型的例子,方法的调用:
package WordCount; public class NoVoid { public static void main(String[] args) { int one = addOne(10, 20); // 调用整数的加法的方法操作 float two = addTwo(10.3f, 13.3f); // 调用浮点的加法的方法操作 System.out.println("addOne的计算结果:" + one); System.out.println("addTwo的计算结果:" + two); } //定义方法,完成两个整数的加法操作,方法返回一个int型数据 public static int addOne(int x,int y){ int temp; //temp为局部变量,只在此方法中有效 temp=x+y; //执行加法计算 return temp; //返回计算结果 } public static float addTwo(float x,float y){ float temp; temp=x+y; return temp; } }
结果:
addOne的计算结果:30
addTwo的计算结果:23.6
2. 方法的重载:
就是方法名称相同,但方法返回的类型和参数的个数、类型不同。通过传递参数的个数及类型的不同可以完成不同功能的方法调用,程序:
package WordCount; import org.omg.CosNaming.NamingContextExtPackage.AddressHelper; public class MethodDemo03 { public static void main(String[] args) { int one = add(10, 20); int two = add(10, 20, 30); float three = add(10.3f, 13.3f); System.out.println("add(int x,int y)的计算结果:" + one); System.out.println("add(int x,int y,int z)的计算结果:" + two); System.out.println("add(float x,float y)的计算结果:" + three); } public static int add(int x,int y) { int temp; temp=x+y; return temp; } public static int add(int x,int y,int z){ int temp; temp=x+y+z; return temp; } public static float add(float x,float y){ float temp; temp= x+y; return temp; } }
结果:
add(int x,int y)的计算结果:30
add(int x,int y,int z)的计算结果:60
add(float x,float y)的计算结果:23.6
add方法被重载了三次,以返回类型和参数来识别应该调用那个方法。
重载注意的事项:
*************************************
但方法返回的类型和参数的个数、类型不同,,,
*************************************