一、方法的返回值
1、说明
就是方法调用结束的标志,会返回一个值给调用该方法的方法里,然后我们常用的就是使用一个变量去接收这个值,并把这个值用作其他的操作。
2、练习代码
public class Test05{
public static void main(String[] args) {
double num = mutiply(13, 14);
System.out.println(num);
}
public static double mutiply(int a, int b){
int c = a * b;
return c;
}
}
3、案例分析:获取数组中最大值的方法
① 定义一个方法,声明两个形参接收计算的数值,求出结果并返回;
② 使用if语句得出数组中各个数之间的最大值,根据情况retum具体结果;
③ 在main0方法中调用定义好的方法并使用变量保存。
4、案例练习
public class Test05{
public static void main(String[] args){
int[] arr1 = {11, 33, 55, 22, 44};
System.out.println("数组中所有元素最大的值为:");
int res = get_max(arr1);
System.out.println(res);
System.out.println("There is bottom!");
}
public static int get_max(int[] arr2){
int max = arr2[0];
for(int i=1; i<arr2.length; i++){
if(arr2[i] > max){
max = arr2[i];
}
}
return max;
}
}
二、方法的重载
1、重载说明
图片:@黑马程序员
2、重载概述
(1)在同一个类中,定义了多个同名的方法,但每个方法具有不同的参数类型或参数个数,这些同名的方法,就成了重载关系。
(2)简述:同一个类中,方法名相同,参数不同的方法(参数不同表现为个数不同、类型不同、顺序不同);
(3)识别方法之间是否是重载关系,只看方法名和参数,跟返回值无关。
(4)方法重载时可以改变参数的顺序,但是这样的重载没什么意义,不建议这样使用。
3、重载的好处——不用记忆过多繁琐的方法名
4、案例分析:比较两个整数的关系><=,兼容全整数类型(byte,short,int,long)
① 定义一个比较的方法compare(),参数选择两个int型参数;
②定义对应的重载方法,变更对应的参数类型,参数变更为两个long型参数;
③ 定义所有的重载方法,两个byte类型与两个short类型参数;
④完成方法的调用,测试运行结果。
5、案例练习
public class Test05{
public static void main(String[] args){
byte a1=10, b1=50;
short a2=99, b2=99;
int a3=12, b3=5;
long a4=12345, b4=23456;
char res1 = compare(a1, b1);
char res2 = compare(a2, b2);
char res3 = compare(a3, b3);
char res4 = compare(a4, b4);
System.out.println(a1 + "和" + b1 + "的关系是:" + a1 + res1 + b1);
System.out.println(a2 + "和" + b2 + "的关系是:" + a2 + res2 + b2);
System.out.println(a3 + "和" + b3 + "的关系是:" + a3 + res3 + b3);
System.out.println(a4 + "和" + b4 + "的关系是:" + a4 + res4 + b4);
System.out.println("==========================There is bottom!============================");
}
public static char compare(byte x1, byte y1){
char bound;
if(x1>y1){
bound = '>';
}else if(x1<y1){
bound = '<';
}else{
bound = '=';
}
return bound;
}
public static char compare(short x1, short y1){
char bound;
if(x1>y1){
bound = '>';
}else if(x1<y1){
bound = '<';
}else{
bound = '=';
}
return bound;
}
public static char compare(int x1, int y1){
char bound;
if(x1>y1){
bound = '>';
}else if(x1<y1){
bound = '<';
}else{
bound = '=';
}
return bound;
}
public static char compare(long x1, long y1){
char bound;
if(x1>y1){
bound = '>';
}else if(x1<y1){
bound = '<';
}else{
bound = '=';
}
return bound;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)