方法的重载
方法重载的概念
重载: 在同一个类中, 出现了方法名相同, 参数列表不同, 与返回值类型无关, 的多个方法.
调用重载的方法: 虚拟机会根据传入参数的不同, 调用不同的方法
方法的重载案例联系
- 定义比较是否相同的方法: 方法名compare()
- 需要兼容所有整数类型
- compare(byte a, byte b)
- compare(short a, short b)
- compare(int a, int b)
- compare(long a, long b)
- public class Demo03 {
public static void main(String[] args) {
System.out.println(compare(10,20));//调用int类型compare方法
System.out.println(compare((byte) 10,(byte)20));//调用byte类型方法
System.out.println(compare((short) 10,(short)20));//调用short类型方法
System.out.println(compare(10L,20L));//调用long类型方法
}
public static boolean compare(byte a , byte b) {
System.out.println("byte");
//方式1
/*if (a == b) {
return true;
}else {
return false;
}*/
//方式二
/*boolean same = a == b ? true : false;
return same;
return a == b ? true : false;*/
//方式三
return a == b;
}
public static boolean compare(short a , short b) {
System.out.println("short");
return a == b;
}
public static boolean compare(int a , int b) {
System.out.println("int");
return a == b;
}
public static boolean compare(long a , long b) {
System.out.println("long");
return a == b;
}
}
方法的参数传递
**基本数据类型**
public class Test04 {
public static void main(String[] args) {
int num = 10;
method(num);
System.out.println("num=" + num);
}
public static void method(int a ) {
a = 20;
System.out.println("a=" + a);
}
}
运行结果:
a=20
num=10
Process finished with exit code 0
**引用数据类型**
public class Test04 {
public static void main(String[] args) {
int[] arr = {10,20,30};
method(arr);
System.out.println(arr[1]);
}
public static void method(int[] arr ) {
arr[1] = 40;
}
}
运行结果:
40
Process finished with exit code 0
参数传递总结:
- 基本数据类型, 形参的改变不影响实参
- 引用数据类型, 形参的改变影响实参