首页 > 技术文章 > 6. java 方法

hq82 2019-10-07 12:08 原文

一、方法定义格式

修饰符 返回值类型 方法名称(参数类型 参数名称, ...){
    方法体;
    return 返回值;
}

1. 修饰符:现阶段固定写法,public static
2. 参数如果有多个,使用逗号进行分隔
3. return:(1)停止当前方法 (2)后面的结果数据返回值还给调用处
4. return后面的返回值,必须和方法名称前面的返回值类型,保持对应
public class Demo{
    public static void main(String[] args){
        
    }
    public static int sum(int a, int b){
        int result = a + b;
        return result;
    }
}

二、方法调用

public class Demo{
    public static void main(String[] args){
        // 单独调用
        sum(10, 20);
        // 打印调用
        System.out.println(sum(10, 20));
        // 赋值调用
        int number = sum(15, 20);
    }
    public static int sum(int a, int b){
        int result = a + b;
        return result;
    }
}

注意:返回值类型固定写为void,这种方法只能"单独调用",不能进行打印调用,或者赋值调用。对于无返回值的方法,只能使用单独调用。Java 中,大家对 void 应该是相当熟悉了。它表示“空”,所有无返回值的方法都使用它表示返回类型。

// 判断两数字是否相同
public class test {
    public static void main(String[] args) {
        System.out.println(compare(1, 2));
    }

    public static boolean compare(int a, int b) {
        boolean same;
        if (a == b) {
            same = true;

        } else {
            same = false;
        }
        return same;
    }
}
public class test {
    public static void main(String[] args) {
        System.out.println(compare(1, 2));
    }

    public static boolean compare(int a, int b) {
        return a == b;
    }
}
public class test {
    public static void main(String[] args) {
        System.out.println(compare(1, 2));
    }

    public static boolean compare(int a, int b) {
        if (a == b) {
            return true;

        } else {
            return false;
        }
    }
}

三、方法重载

方法重载(overlord):多个方法的名称一样,但是参数列表不一样。
public class MethodDemo {
    public static void main(String[] args) {
        // 下面是针对求和方法的调用
        int sum1 = add(1, 2);
        int sum2 = add(1, 2, 3);
        double sum3 = add(1.2, 2.3);
        // 下面的代码是打印求和的结果
        System.out.println("sum1=" + sum1);
        System.out.println("sum2=" + sum2);
        System.out.println("sum3=" + sum3);
    }

    // 下面的方法实现了两个整数相加
    public static int add(int x, int y) {
        return x + y;
    }
    // 下面的方法实现了三个整数相加
public static int add(int x, int y, int z) {
        return x + y + z;
    }
    // 下面的方法实现了两个小数相加
    public static double add(double x, double y) {
        return x + y;
    }
}

上述代码中定义了三个同名的add()方法,它们的参数个数或类型不同,从而形成了方法的重载。在main()方法中调用add()方法时,通过传入不同的参数便可以确定调用哪个重载的方法。

注意事项:

  • 重载方法参数必须不同:

    • 参数个数不同,如method(int x)与method(int x,int y)不同

    • 参数类型不同,如method(int x)与method(double x)不同g

    • 参数顺序不同,如method(int x,double y)与method(double x,int y)不同

  • 重载只与方法名与参数类型相关与返回值无关

    • 如void method(int x)与int method(int y)不是方法重载,不能同时存在
  • 重载与具体的变量标识符无关

  • 如method(int x)与method(int y)不是方法重载,不能同时存在

推荐阅读