Java方法
2021/10/25 22:40:10
本文主要是介绍Java方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Java 方法
什么是方法
方法是什么?
- System.out.println()是什么?
- System是一个类,out是一个对象,println是方法
- 方法是语句的集合,一起执行一个功能
- 方法是解决一类问题的步骤的有序集合
- 方法包含于类和对象中
- 方法在程序中创建,在其他地方被引用
- 设计原则:
- 方法要有原子性,一个方法尽可能完成一个功能
public class Demon01 { //main方法 public static void main(String[] args) { System.out.println(add(3,5)); } //加法 public static int add(int a, int b){ return a+b; } }
方法的定义和调用
方法的定义
- java的方法即其他语言的函数。
- 方法包含一个方法头和方法体,下面是全部部分:
- 修饰符:static等
- 返回值类型
- 方法名:遵守驼峰命名
- 参数类型:参数是占位符,传递的值是实参,形参只是用于占位的。
- 方法体
- 返回值
方法的调用
- 调用方法:对象名.方法名(实参列表)
- Java支持两种调用:
- 有返回值直接当成一个值使用
- 无返回值就当成一个语句使用
- 值传递(Java没有指针操作)和引用传递
public class Demon02 { public static void main(String[] args) { int res = max(10, 20); System.out.println(res); } public static int max(int a, int b){ int res = -1; if(a>=b) res = a; else res = b; return res; } }
方法的重载
- 重载:
- 在同一个类中,有同名但是不同参数/参数类型的方法
- 重载的规则:
- 方法名称必须相同
- 参数列表必须不同(参数类型,参数个数)
- 方法返回类型可以相同也可以不同
- 仅仅返回类型不同不足以重载
public class Demon02 { public static void main(String[] args) { int res = max(10, 20); System.out.println(res); } public static int max(int a, int b){ int res = -1; if(a>=b) res = a; else res = b; return res; } //方法重载 public static double max(double a, double b){ double res = -1; if(a>=b) res = a; else res = b; return res; } }
命令行传递参数
- 有时候希望运行一个程序再传递给他消息,要依靠传递命令行参数给main()函数实现
- 需要编译后用命令行执行传参
public class Demon03 { public static void main(String[] args) { //args.length for(int i=0;i<args.length;i++){ System.out.println("args["+ i +"]:" + args[i]); } } }
可变参数
- 在方法声明中,在指定参数类型后加一个省略号(...)
- 一个方法中只能指定一个可变参数
- 可变长参数只能在参数表中最后一个参数
public class Demon04 { public static void main(String[] args) { Demon04 demon04 = new Demon04(); demon04.test(1,2,3,4,5); } public void test(int... i){ System.out.println(i); } }
递归讲解
- 递归就是方法本身调用方法自己。
- 利用递归可以用简单的程序来解决一些复杂的问题。
- 递归包括两个部分:
- 递归头:递归什么时候开始
- 递归尾:递归什么时候结束
- 递归的实现是通过栈实现的,过深会造成巨大开销
public class Demon05 { public static void main(String[] args) { fun(5); } public static int fun(int n){ if(n==1){ return 1; }else{ return fun(n-1)*n; } } }
这篇关于Java方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求