Java 方法重载:参数类型不匹配导致错误
类Test1定义如下: public class Test1{ public float aMethod(float a,float b){ } } 将以下哪种方法插入行3是不合法的。( ) A、public float aMethod(float a, float b,float c){ } B、private float aMethod(int a,int b,int c){ } C、public float aMethod(float c,float d){ } D、public int aMethod(int a, int b){ }
答案:B、private float aMethod(int a,int b,int c){ }
解释:
Java 中的方法重载是指在同一个类中定义多个同名方法,但这些方法必须具有不同的参数列表。参数列表的不同可以体现在参数的类型、个数或顺序上。
在示例中,原始方法 aMethod 接受两个 float 类型参数。选项 B 中的方法 aMethod 接受三个 int 类型参数,与原始方法的参数类型不匹配,因此无法构成方法重载,编译时会报错。
选项 A、C、D 中的方法都满足方法重载的条件,因为它们的返回值类型或参数列表与原始方法有所区别。
原文地址: https://www.cveoy.top/t/topic/oFgX 著作权归作者所有。请勿转载和采集!