大龄屌丝自学笔记--Java零基础到菜鸟--012

方法,重载

 

1、方法:完成特定功能的代码块

格式:修饰符 返回值 方法名(参数类型 参数名1, ...... ,参数类型 参数名n){ 函数体; return 返回值; } 。

注意:“void” 方法不需要返回值,方法不能嵌套。

 1 class Fin{
 2 
 3     //main方法
 4     public static void main(String[] args){
 5         int n=test(3,2);        //调用test方法
 6         System.out.println(n);  //n=1  
 7     }
 8 
 9     //test方法
10     public static int test(int a,int b){
11          return a-b;
12     }
13 }

 

2、重载:同一个类中,允许同名不同参数(参数类型或参数个数不同)的方法

注意:与方法的返回值无关,只看方法名和参数(参数类型、参数个数),通过参数区分同名方法。

 1 class Fin{
 2     public static void main(String[] args){
 3         int n=test(3,2,1);
 4         System.out.println(n);  //n=6
 5     }
 6 
 7     public static int test(int a,int b){
 8         return a-b;
 9     }
10 
11     public static int test(int a,int b,int c){
12         return a+b+c;
13     }
14 }
posted @ 2015-08-26 22:00  ilmari  阅读(149)  评论(0编辑  收藏  举报