作者:手机用户2502858701 | 来源:互联网 | 2023-06-01 16:18
什么是方法
也是函数,说得很抽象,看图
没使用方法:每次要矿泉水都要写将水装入瓶子中的代码,要100瓶就要写100次代码
方法=矿泉水工厂
使用方法:把将水装入瓶子这个步骤代码写在方法里,要100瓶只要直接调用100次方法就行,避免写重复代码
语法
修饰符 返回值类型 方法名(参数类型 参数名){
方法体
return 返回值;
}
方法名:能体现该方法的作用
参数名:图中的水和瓶子
方法体:将水装入瓶子
返回值:矿泉水
代码
public class Method {public int sum(int a,int b){ int c = a + b;return c;}public static void main(String[] args) {Method method = new Method(); int ab = method.sum(1,1); System.out.println(ab);}
}
流程:int ab = method.sum(1,1); 将两个1赋值给方法中的a和b方法返回c=2赋值给ab
重载
方法名相同,参数不同或类型不同
public class Method {public int sum(int a,int b){ int c = a + b;return c;}public int sum(int a,int b,int c){ int d = a + b + c;return d;}public static void main(String[] args) {Method method = new Method(); int ab = method.sum(1,1); int abc = method.sum(1,1,1); System.out.println(ab);System.out.println(abc);}
}