2020/10/10 刘一辰的JAVA随笔
今日目标:同一个 类 中,出现名称相同的多个方法,但是多个方法的形参列表是不同的,我们称为这些方法是重载方法。
实验代码:
运用 Java 方法重载,分别定义形参列表 为不同 整数类型 的 方法。
- Java 的整数类型分别为 byte、short、int、long。
- 定义 4 个名字一样,形参分别为 byte、short、int、long 的方法。
- 主方法调用这 4 个方法。
public class OverrideDmeo01
{
public static void main(String[] args)
{
compare((byte)1,(byte)1);
// 调用形参为 short 的方法
compare((short)1,(short)1);
// 调用形参为 int 的方法
compare(1,1);
// 调用形参为 long 的方法
compare(1L,1L);
}
public static boolean compare(byte a , byte b)
{
System.out.println("方法形参为 byte");
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 ;
}
}
以上案例展示的就是 Java 方法重载。