Java 函数

什么是函数

函数:具有名称为了实现某一特定功能的代码的集合
封装代码,提高代码的复用性。

如何定义函数。

语法结构

访问修饰符 返回值的类型 函数名称([参数列表]) {
	// 函数体 
	[return 返回值;]
}

函数调用

public class TestFun {
	public static void main(String[] args) {
		showInfo();
	}
	
	public static void showInfo() {
		System.out.println("hello world");
	}
}

函数分类

|-- 通过是否存在参数
	|-- 有参函数
	|-- 无参函数
public class TestFun {
	public static void main(String[] args) {
		showInfo("hello world");
	}
	
	public static void showInfo(String s) {//有参函数
		System.out.println(s);
	}
}
|--有无返回值
	|-- 有返回值的函数
	|-- 无返回值函数
public class TestFun {
	public static void main(String[] args) {
		System.out.println(showInfo);
	}
	
	public static String showInfo() {//有参函数
		//返回String 类型对象
		return "hellow world";
	}
}

局部变量(本地变量):

定义在函数内部的变量
public class TestFun {
public static void main(String[] args) {
	System.out.println(showInfo);
}

public static String showInfo() {//有参函数
	//返回String 类型对象
	String s= "hellow world"; 	//局部变量使用之前必须赋值
	return s;
}

}

函数的重载(overload)

函数的重载现象,只存在于强数据类型语言中(java、c、c++),弱数据类型语言不存在(如:JavaScript、PHP、python)指的是,多个函数之间的一种关系,函数名称相同,函数参数的类型的或者参数的个数的不同。

注意:重写(overwrite)<==>覆盖(override)这些概念,这两个是一个意思,是面向对象中继承里面的概念,跟重载没有关系

public class TestFun {
	public static void main(String[] args) {
		//重载函数包含的参数类型不同
		testOverLoad();//调用第一个重载
		testOverLoad(1);//调用第二个重载
		testOverLoad(2.5);//调用第三个重载

		//重载函数包含的参数类型相同但顺序不同
		testOverLoad(3,3.5);
		testOverLoad(4.5,6);
	}
	
	public static void testOverLoad() {
		System.out.println("重载函数一");
	}
	public static void testOverLoad(int t) {
		System.out.println(t);
		System.out.println("重载函数二");
	}
	public static void testOverLoad(double t) {
		System.out.println(t);
		System.out.println("重载函数三");
	}
	public static void testOverLoad(int i,double t) {
		System.out.println(i);
		System.out.println(t);
		System.out.println("重载函数四");
	}
	public static void testOverLoad(double t,int i) {
		System.out.println(t);
		System.out.println(i);
		System.out.println("重载函数五");
	}
}

递归:

函数自身调用自身这种现象叫做递归,递归是一种分治思想的体现。函数递归时必须有结束递归的判断。

public class TestFun {
	public static void main(String[] args) {
		System.out.println(sum(100)); //输出5050
	}
	
	//返回1到i的自然数的和
	public static int sum(int i) {
		if (i==1) { //结束递归的判断
			return 1;
		}
		return i+sum(i-1);
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值