第8篇:学习 Java 中的方法(方法的定义、可变参数、参数的传递问题、方法重载、方法签名)通过官方教程

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

@TOC

一、方法(Method)概念

:pencil2: 1、Java 中的方法就是其他编程语言中的函数(Function)
:pencil2: 2、方法的定义格式:
在这里插入图片描述

:books: ① 访问修饰符有4种:public、protected、default、private【 后期会详细说明
:books: ② 返回值类型可能是8大基本数据类型、引用类型或无返回值( void
:books: ③ 方法名需符合标识符命名规范、方法名需见名知意、方法名需是小驼峰(类名是大驼峰)
:books: ④ 参数列表是该方法需要调用者传入的值(包括参数类型和参数名)【 后期会详细说明
:books: ⑤ 方法体中才可编写 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);
    }

}
其实可以理解为只有三个地方是代码块:
:star: ① 代码块
:star: ② 静态代码块
:star: ③ 方法中
但是,当初老师教的时候把 if、while、for 等也归纳为方法体

在这里插入图片描述
:seedling: 补充:定义方法可能还会有其他修饰符(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;
}

结束,下篇文章见哦!

相关文章
|
1天前
|
XML 自然语言处理 安全
Java 中文官方教程 2022 版(四十九)(3)
Java 中文官方教程 2022 版(四十九)
6 0
|
1天前
|
XML Java 编译器
Java 中文官方教程 2022 版(四十九)(2)
Java 中文官方教程 2022 版(四十九)
6 0
|
1天前
|
安全 Java 编译器
Java 中文官方教程 2022 版(四十六)(2)
Java 中文官方教程 2022 版(四十六)
6 0
|
1天前
|
存储 Java 编译器
Java 中文官方教程 2022 版(四十四)(4)
Java 中文官方教程 2022 版(四十四)
6 0
|
1天前
|
安全 Java 编译器
Java 中文官方教程 2022 版(四十三)(3)
Java 中文官方教程 2022 版(四十三)
8 1
|
1天前
|
安全 数据可视化 Java
Java 中文官方教程 2022 版(四十三)(1)
Java 中文官方教程 2022 版(四十三)
8 1
|
1天前
|
XML JavaScript Java
Java 中文官方教程 2022 版(四十)(4)
Java 中文官方教程 2022 版(四十)
7 0
|
1天前
|
XML JavaScript Java
Java 中文官方教程 2022 版(三十九)(1)
Java 中文官方教程 2022 版(三十九)
6 0
|
1天前
|
存储 自然语言处理 Oracle
Java 中文官方教程 2022 版(三十一)(2)
Java 中文官方教程 2022 版(三十一)
9 2
|
1天前
|
存储 小程序 Java
Java 中文官方教程 2022 版(三十一)(1)
Java 中文官方教程 2022 版(三十一)
12 4

热门文章

最新文章