Java 方法(方法的定义,可变参数,参数的传递问题,方法重载,方法签名)

 更新时间:2022年09月09日 17:01:41   作者:new Handsome()  
这篇文章主要介绍了Java 方法(方法的定义,可变参数,参数的传递问题,方法重载,方法签名),文章围绕主题展开详细的内容介绍,具有一定的参考价值,感兴趣的小伙伴可以参考一下

一、方法(Method)概念

  •  1、Java 中的方法就是其他编程语言中的函数(Function)
  •  2、方法的定义格式:

  • 访问修饰符有4种:public、protected、default、private【后期会详细说明】
  • 返回值类型可能是8大基本数据类型、引用类型或无返回值(void
  • 方法名需符合标识符命名规范、方法名需见名知意、方法名需是小驼峰(类名是大驼峰)
  • 参数列表是该方法需要调用者传入的值(包括参数类型和参数名)【后期会详细说明】
  • 方法体中才可编写 Java 语句(并不是所有花括号中都是方法体:如类定义的花括号中不是方法体)

下面是方法体代码案例:

public class MethodBody {

    // 1.代码块
    {
        System.out.println("【{}】是方法体");
    }

    // 2.静态代码块
    static {
        System.out.println("【static {}】是方法体");
    }

    // 3.方法
    public void run(int age) {
        System.out.println("方法的花括号中是方法体");

        // 4.if
        if (age == 18) {
            System.out.println("if 语句的花括号中是方法体");
        }

        // 5.for
        for (int i = 0; i < age; i++) {
            System.out.println("for 循环的花括号中是方法体");
        }

        // 6.while
        while (age > 50) {
            System.out.println("while 循环的花括号中是方法体");
        }

        // 7.switch-case
        switch (age) {
            // 错误:在该区域写代码是错误的(该区域不是方法体)
            // System.out.println(age); // ERROR
            case 1: {
                System.out.println("switch 语句的 case 语句块是方法体");
            }
        }

        // 8.do-while
        do {
            System.out.println("do-while 循环的花括号中是方法体");
        } while (age < 5);
    }

}

其实可以理解为只有三个地方是代码块:

① 代码块
② 静态代码块
③ 方法中
但是,当初老师教的时候把 if、while、for 等也归纳为方法体

补充:定义方法可能还会有其他修饰符(eg:static、final、abstract),后面还会详细介绍

仔细看下面的代码, 学会定义方法:

public class CreateMethodDemo {
    public static void main(String[] args) {
        int sum1 = CreateMethodDemo.sumOne2Hundred(1, 100);
        // sum1 = 5050
        System.out.println("sum1 = " + sum1);

        int sum2 = CreateMethodDemo.sumOne2Hundred(1, 1000);
        // sum2 = 500500
        System.out.println("sum2 = " + sum2);

        int sum3 = CreateMethodDemo.sumOne2Hundred(1, 10000);
        // sum3 = 50005000
        System.out.println("sum3 = " + sum3);
    }
    /**
     * 计算[start, end]的累加和
     *
     * @param start 起始值
     * @param end   结束值
     * @return [start, end]的累加和
     */
    private static int sumOne2Hundred(int start, int end) {
        int sum = 0;

        for (int i = start; i <= end; i++) {
            sum += i;
        }
        return sum;
    }
}

二、可变参数(Variable)

思考:编写程序计算多个整数的和。eg:计算【2, 5, 6, 7, 66, 53】的和

public class VariableParameter {
    public static void main(String[] args) {
        int[] arr = {2, 5, 6, 7, 66, 53};
        VariableParameter vp = new VariableParameter();
        // sumByArr = 139
        System.out.println(vp.sumByArr(arr));
    }

    /**
     * 计算多个整数的和(通过数组)
     *
     * @param arr (数组中存放需要进行求和的多个整数)
     * @return 数组中多个整数的和(类型是字符串)
     */
    private String sumByArr(int[] arr) {
        if (arr == null || arr.length < 1) return "arr 数组为 null, 为数组元素为 0";

        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        return "sumByArr = " + sum; 
    }
}

思路1:
🌟可把需要进行求和的整数放入一个整型数组中,并把整型数组作为参数传给 sumByArr 方法
🌟sumByArr 方法接收一个 int 类型的数组作为参数,在 sumByArr 的方法体中通过 for 循环遍历数组中的数字,并进行求和
思路2:
🌻使用可变参数替换 arr 数组

public class VariableParameter {

    public static void main(String[] args) {
        VariableParameter vp = new VariableParameter();
        // 当 sumByVariable1Parameter 的参数列表中一个【值】都没有
        // 的时候, 返回值是可变参数类型的默认值
        int sum = vp.sumByVariable1Parameter(2, 5, 6, 7, 66, 53);
        // sumByVariable1Parameter = 139
        System.out.println("sumByVariable1Parameter = " + sum);
    }

    /**
     * 计算多个整数的和(通过可变参数)
     *
     * @param nums (参数列表中可以放多个需要进行求和的整数)
     * @return 参数列表中多个整数的和(类型 int)
     */
    private int sumByVariable1Parameter(int... nums) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
        }
        return sum;
    }
}
  • 可变参数的本质是数组
  • 可变参数必须是方法的参数列表中的最后一个参数

String 类有静态方法 format 可用于拼接字符,它的底层就用到了【可变参数】

public class VariableParameter {

    public static void main(String[] args) {
        String info = String.format("name: %s; age: %d; money: %f", 
    							"庆医", 10, 895863.99);
        // info = name: 庆医; age: 10; money: 895863.990000
        System.out.println("info = " + info);
    }
}

三、方法的参数传递问题

1. 基本数据类型

Passing Primitive Data Type Arguments 传递原始数据类型参数

  • 基本类型作为参数是值传递
  • 基本类型作为返回值,返回的是值本身
  • 基本类型:byte、short、int、long、float、double、boolean、char

Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost.

原始参数(eg:int 或 double)通过 value 传递给方法。这意味着对参数值的任何更改仅存在于该方法的作用域内。当方法返回后,栈帧销毁后,参数消失后,对它们的任何更改都将无效。

public class ArgumentsPassingTest {

    public static void main(String[] args) {
        int n = 10;
        test(n); // 值传递(v 和 n 没有关系)
        // n = 10
        System.out.println("n = " + n);
    }
    private static void test(int v) { // v = 10
        v = 20;
    }
}

基本类型作为返回值,返回的是值本身:

public class ArgumentsPassingTest {

    public static void main(String[] args) {
        int test = test(66);
        // test = 88
        System.out.println("test = " + test);
    }

    private static int test(int param) {
        param = 88;
        return param;
    }
}

2. 引用数据类型

Passing Reference Data Type Arguments(传递引用数据类型参数)

  • 引用类型作为参数是引用传递(地址传递)
  • 引用类型作为返回值是引用传递(地址传递

Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object’s fields can be changed in the method, if they have the proper access level.
引用数据类型参数(例如对象)也按值传递给方法。这意味着当方法返回时,传入的引用仍然引用着与之前相同的对象。但是,如果对象字段的值具有适当的访问级别,则可以在方法中更改它们。

public class ArgumentsPassingTest {

    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        test(nums);
        // nums = [1, 66, 3]
        System.out.println("nums = " + Arrays.toString(nums));
    }
    private static void test(int[] param) {
        param[1] = 66;
    }
}

引用类型作为返回值是引用传递(地址传递):

public class ArgumentsPassingTest {

    public static void main(String[] args) {
        int[] test = test();

        // test = [1314, 520, 666]
        System.out.println("test = " + Arrays.toString(test));
    }
    private static int[] test() {
        int[] ints = {1314, 520, 666};
        return ints;
    }
}

栈帧销毁销毁的是局部变量信息,堆空间的对象不会被回收的。

四、方法签名(Method Signature)

方法签名只由2部分组成:方法名、参数类型

private static void test(double pai, String name, int age) {
    return null;
}
  • 上面方法的方法签名是:test(double, String, int)
  • 在同一个类中,方法签名是唯一的(同一方法签名在同一个类中只能出现一次)

五、方法的重载(Overload) 

官方教程:

Overloaded(重载) methods are differentiated by the number and the type of the arguments passed into the method. For example: run(String s) and run(int i) are distinct and unique methods because they require different argument types.

重载的方法通过传递给方法的参数的数量和类型来区分。
例如:run(String s)run(int i) 是不同且独特的方法,因为它们拥有不同的参数类型

重载:

  • ① 方法名相同,参数类型或数量不同;
  • ② 重载与返回值类型、参数名称无关

The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
编译器在区分方法时不考虑返回类型,因此即使它们具有不同的返回类型,也不能声明具有相同签名的两个方法。

You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.
您不能声明多个具有相同名称和相同数量和类型的参数的方法,因为编译器无法区分它们。

下面的两个方法构成方法重载:

private static int[] test(double weight, String name, int age) {
    return null;
}
private static int[] test(int age, double weight, String name) {
    return null;
}

到此这篇关于Java 方法(方法的定义,可变参数,参数的传递问题,方法重载,方法签名)的文章就介绍到这了,更多相关Java方法定义内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java实现复制文件并命名的超简洁写法

    Java实现复制文件并命名的超简洁写法

    这篇文章主要介绍了Java实现复制文件并命名的超简洁写法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • 新手学习微服务SpringCloud项目架构搭建方法

    新手学习微服务SpringCloud项目架构搭建方法

    这篇文章主要介绍了新手学习微服务SpringCloud项目架构搭建方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-01-01
  • Java超详细讲解三大特性之一的继承

    Java超详细讲解三大特性之一的继承

    继承就是可以直接使用前辈的属性和方法。自然界如果没有继承,那一切都是处于混沌状态。多态是同一个行为具有多个不同表现形式或形态的能力。多态就是同一个接口,使用不同的实例而执行不同操作
    2022-05-05
  • Spring利用注解整合Mybatis的方法详解

    Spring利用注解整合Mybatis的方法详解

    这篇文章主要为大家介绍了Spring如何利用注解整合MyBatis,文中的示例代码讲解详细,对我们学习有一定的参考价值,需要的小伙伴可以参考一下
    2022-06-06
  • Spring Data JPA例子代码[基于Spring Boot、Mysql]

    Spring Data JPA例子代码[基于Spring Boot、Mysql]

    这篇文章主要介绍了Spring Data JPA例子代码[基于Spring Boot、Mysql],小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-04-04
  • 带大家深入了解Spring事务

    带大家深入了解Spring事务

    Spring框架提供统一的事务抽象,通过统一的编程模型使得应用程序可以很容易地在不同的事务框架之间进行切换. 在学习Spring事务前,我们先对数据库事务进行简单的介绍。,需要的朋友可以参考下
    2021-05-05
  • KotlinScript构建SpringBootStarter保姆级教程

    KotlinScript构建SpringBootStarter保姆级教程

    这篇文章主要为大家介绍了KotlinScript构建SpringBootStarter的保姆级教程,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • java将数据写入内存,磁盘的方法

    java将数据写入内存,磁盘的方法

    下面小编就为大家分享一篇java将数据写入内存,磁盘的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-01-01
  • Java用 Rhino/Nashorn 代替第三方 JSON 转换库

    Java用 Rhino/Nashorn 代替第三方 JSON 转换库

    本篇文章主要介绍了Java用 Rhino/Nashorn 代替第三方 JSON 转换库,非常具有实用价值,需要的朋友可以参考下
    2017-05-05
  • Map与JavaBean相互转换的工具类 

    Map与JavaBean相互转换的工具类 

    这篇文章主要介绍了Map与JavaBean相互转换的工具类,在做导入的时候,遇到了需要将map对象转化 成javabean的问题,也就是说,不清楚javabean的内部字段排列,只知道map的 key代表javabean的字段名,value代表值,需要的朋友可以参考下
    2022-02-02

最新评论