1. 方法的定义
方法:对功能或者动作的封装
public static void 方法名 ( ){
方法体
}
public static void 照着写。
不可以在方法里定义方法!
public class TestMethod {
/**
* 定义一个方法 fun
* 只是定义方法,没有调用
*/
public static void fun(){
System.out.println("成功调用方法 fun");
}
//主方法, 主函数, 程序的入口
public static void main(String[] args) {
//调用方法
fun();
}
}
2. 方法的返回值
public static 返回值类型 方法名 ( ){
方法体
return 值 ;
}
public class TestMethod2 {
public static String buy(){
System.out.println("我要去买烟了");
//需要使用 return 返回
return "中华香烟";
}
public static void main(String[] args) {
String yan = buy();
System.out.println("得到的返回值是"+yan);
}
}
void型可不写 return ,或 return 后不跟值。
return 后不可再写代码。
3. 方法的参数
public static 返回值类型 方法名 ( 形参 ){
方法体
return 值 ;
}
方法 ( 实参 )
形参: 接收数据
实参: 传递信息
public class TestMethod3 {
/**
*
* @param tools
* @param guanxi
*/
public static void yue(String tools , String guanxi){
System.out.println("使用"+tools);
System.out.println("1.拿出手机");
System.out.println("2.打开"+tools);
System.out.println("3.找到一个"+guanxi);
System.out.println("4.出来聊聊天,看看电影");
}
public static void main(String[] args) {
// 用一次陌陌,一次探探
yue("微信","朋友");
yue("QQ","家人");
}
}
4. 方法的重载
方法的名字相同,参数的个数或类型不同。和返回值没有关系。
在执行的时候,程序会根据参数找对应的方法。
public class TestMethod4 {
public static void chi(String fan){
System.out.println("吃"+fan);
}
public static void chi(String fan, String cai){
System.out.println("吃"+fan+"和"+cai);
}
public static void main(String[] args) {
chi("米饭");
chi("米饭","鱼香肉丝");
}
}