Java学习笔记二

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("米饭","鱼香肉丝");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值