java - 方法

提高代码的复用性,完成特定功能的代码块。

格式

修饰符 返回值类型 方法名(参数类型 参数名1,参数类型 参数名2...) {
	方法体语句;
	return 返回值; 
} 
修饰符:publc、protected、private...
返回值类型:返回值的数据类型
方法名:符合命名规范的名字
():参数
参数类型:参数的数据类型
参数名:形参
方法体语句:方法要实现的功能代码
return:结束方法
返回值:功能代码实现的结果,由return带给调用者

public static void log(){
	System.out.println("不能用单引号很不习惯");
}
log();//输出 不能用单引号很不习惯

public static  void sum(int a , int b){
	int c = a + b;
	return c;
}
System.out.println(sum(1,2));//3

public static void str(int a){
	if(a > 10){
		System.out.println(a + "> 10“);
		return;
	}
	System.out.orintln(a + "< 10");
}
str(2);//a<10
str(20);//a>10

方法重载

在同一个类中,方法名相同,参数列表不同。与返回值类型无关。
参数个数不同
参数类型不同
double sum1 = add(10,20.1);
System.out.println(sum1);

int sum2 = add(10,20,30);
System.out.println(sum2);

double sum3 = add(12.3,13);
System.out.println(sum3);

public static double add(int a,double b) {
	return a + b;
}
public static int add(int a,int b,int c) {
	return a + b + c;
}
public static double add(double a,int b) {
	return a + b;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值