一、概念
方法之间的关系
二、条件
1.在同一个类中
2.方法名必须一致
3.参数列表的个数或者类型不一致
4.与返回值无关
三、好处
系统会根据实参类型自动匹配到对应的方法中
四、应用场景
在同一个类中,多个方法功能大概一致,但是细节实现不一 致,就可以考虑使用重载
public class Test04{ /** 需求1:设计一个方法,传入两个int值,返回最大值 -- getMax(int a,int b) 需求2:设计一个方法,传入三个int值,返回最大值 -- getMax(int a,int b,int c) 需求3:设计一个方法,传入两个double值,返回最大值 -- getMax(double a,double b) 需求4:设计一个方法,传入三个double值,返回最大值 -- getMax(double a,double b,double c) 设计方法的步骤: 1.考虑方法名(见名知意) 2.考虑形参(几个?类型?) 3.考虑返回值(需不需要?返回值类型) */ public static void main(String[] args){ //打印getMax方法,前提是该方法必须有返回值 System.out.println(getMax(10.1,20,30)); } public static int getMax(int a,int b){ return (a>b)?a:b; } public static int getMax(int a,int b,int c){ int max = (a>b)?a:b; max = (max>c)?max:c; return max; } public static double getMax(double a,double b){ return (a>b)?a:b; } public static double getMax(double a,double b,double c){ double max = (a>b)?a:b; max = (max>c)?max:c; return max; } //错误示范:重载要关注形参的类型,不关注形参的名字 //public static void method(String str,int i){ //} //public static void method(String ss,int ii){ //} }