当前位置: 首页 > news >正文

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

💰 写了一段时间的 Java 程序,SpringBoot 🍃项目也做了好几个,但感觉自己对 Java 的了解还是特别少,所以决定从🍼开始重新学习,下面是学习的笔记。【学习素材:韩顺平老师】

💰 我会把我的学习过程分为六个阶段:
🍎① Java 和基于 Java 的编程基础(包括 Java 的基本介绍、变量和运算符、程序控制结构、数组、排序、查找)
🍉② Java 的面向对象编程详解
🍏③ 枚举注解、异常、常用类
🍓④ 集合、泛型、多线程
🍑⑤ IO 流和网络编程
🍍⑥ 反射和正则表达式

文章目录

  • 一、方法(Method)概念
  • 二、可变参数(Variable)
  • 三、方法的参数传递问题
    • 1. 基本数据类型
    • 2. 引用数据类型
  • 四、方法签名(Method Signature)
  • 五、方法的重载(Overload)

一、方法(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;
}

结束,下篇文章见哦!

相关文章:

  • 数据库基本结论
  • Django-(3)
  • HyperLynx(十五)多板仿真
  • ElasticSearch(四):ES nested嵌套文档与父子文档处理
  • java 基于springboot员工实训项目管理系统
  • SaaS行业的六大安全问题
  • Geoserver+Cesium 发布带样式矢量数据
  • 【C语言】数据类型、存储类
  • 免关注阅读CSDN博客和复制代码(2022.9.1)
  • shell脚本(四)处理用户输入
  • 08 SpringMVC跨域请求
  • Mac下根目录和home目录的区别
  • 猿创征文|opencv对滤波的处理
  • 输入年月日判断是本年的第多少天
  • 每天一个前端小知识01——Webpack
  • [译] React v16.8: 含有Hooks的版本
  • “Material Design”设计规范在 ComponentOne For WinForm 的全新尝试!
  • 【跃迁之路】【699天】程序员高效学习方法论探索系列(实验阶段456-2019.1.19)...
  • Asm.js的简单介绍
  • JSONP原理
  • LeetCode算法系列_0891_子序列宽度之和
  • Linux gpio口使用方法
  • MYSQL 的 IF 函数
  • Node 版本管理
  • Objective-C 中关联引用的概念
  • Python - 闭包Closure
  • Swift 中的尾递归和蹦床
  • web标准化(下)
  • XML已死 ?
  • 包装类对象
  • 机器学习中为什么要做归一化normalization
  • 来,膜拜下android roadmap,强大的执行力
  • 前端每日实战:70# 视频演示如何用纯 CSS 创作一只徘徊的果冻怪兽
  • 手机端车牌号码键盘的vue组件
  • 原生Ajax
  • 正则表达式
  • 自定义函数
  • mysql面试题分组并合并列
  • ​ 全球云科技基础设施:亚马逊云科技的海外服务器网络如何演进
  • ​什么是bug?bug的源头在哪里?
  • #define,static,const,三种常量的区别
  • #stm32整理(一)flash读写
  • #WEB前端(HTML属性)
  • #绘制圆心_R语言——绘制一个诚意满满的圆 祝你2021圆圆满满
  • (2)MFC+openGL单文档框架glFrame
  • (分布式缓存)Redis分片集群
  • (一)Neo4j下载安装以及初次使用
  • ***php进行支付宝开发中return_url和notify_url的区别分析
  • .NET 8 编写 LiteDB vs SQLite 数据库 CRUD 接口性能测试(准备篇)
  • .NET Core IdentityServer4实战-开篇介绍与规划
  • .NET Core Web APi类库如何内嵌运行?
  • .NET Core 网络数据采集 -- 使用AngleSharp做html解析
  • .NET HttpWebRequest、WebClient、HttpClient
  • .Net6 Api Swagger配置
  • @NoArgsConstructor和@AllArgsConstructor,@Builder