方法的定义格式以及格式的解释

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

 

2.方法的格式:

       修饰符  返回值类型  方法名(参数类型 参数名1,参数类型 参数名2){

       方法体;

       return 返回值;

    }

3.格式解释:

          A:修饰符   public static(等等)

          B:返回值类型  用于限定返回值的数据类型(没有返回值用void修饰,void修饰的方法只能单独调用)

          C:方法名  方便调用

                  c:有明确返回值的方法,单独调用没有意义

                  c:输出调用

                  c:赋值调用(推荐使用)

          D:参数类型     用于限定调用方法时传入的数据类型

          E:参数名   用于接收调用方法时传入的数据的变量

          F:方法体   完成功能的代码块

          G:return    结束方法,并把返回值带给调用者

 

4.求和方法举例:

          
    public static void main(String[] args) {
        int i=sum(10,10);
        System.out.println(i);
    }
    public static int sum(int a,int b) {
        int c=a+b;
        return c;
    }

5.方法的重载:

            A:参数名相同

            B:参数列表不同:

                           a:参数的个数不同

                           b:参数的数据类型不同

四个重载方法在main方法中的调用:

  
    public static void main(String[] args) {
        System.out.println(compare(10,20));
        System.out.println(compare((byte)10,(byte)20));
        System.out.println(compare((short)10,(short)20));
        System.out.println(compare(10L,20L));
        
    }
    public static boolean compare(byte a,byte b) {
        System.out.println("byte");
        return a==b;
    }

    public static boolean compare(short a,short b) {
        System.out.println("short");
        return a==b;
    }
    
    public static boolean compare(int a,int b) {
        System.out.println("int");
        return a==b;
    }
    
    public static boolean compare(long a,long b) {
        System.out.println("long");
        return a==b;
    }

 

6.注意事项:

                   形式参数:用于接收实际参数的变量

                   实际参数:实际参与运算的的变量

                   A:方法的参数如果时候基本数据类型,形式参数的改变不影响实际参数

                   B:方法的参数如果是引用数据类型,形式参数的改变直接影响实际参数

posted @ 2018-12-26 17:31  温火煮红茶  阅读(1051)  评论(0编辑  收藏  举报