java参数重写顺序
根据javadoc
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.
我的问题是——参数的顺序是否无关紧要?如果他们有相同的名字,他们也是相同的类型
# 1 楼答案
如果顺序不相同,编译器将无法找到该方法,并且您将得到一个这样的错误
# 2 楼答案
不,顺序很重要
Java中重写方法的规则
规则1)如果扩展另一个类的类定义了具有相同名称和参数列表的方法,则称该方法被重写
规则2)基类中定义的方法应该在派生类中可见。如果不是这样,则派生类中的方法将不会被视为重写版本,而是被视为普通方法
规则3)重写和重写方法的方法名和参数列表应相同。但是返回类型可以是co-variant。这意味着如果超类中方法的返回类型为 Map,则同一方法的返回类型可以是HashMap
规则4)重写方法(在派生类中)中的访问说明符不应比重写方法(在基类中)中的访问说明符更具限制性。这意味着,如果基类方法的访问说明符受保护,则派生类方法的访问说明符不应是默认的或私有的,而可以是受保护的、公共的。增加各种说明符可见性的顺序是:
私有、默认、受保护、公共
规则5)派生类方法中指定的异常应该是它们的相同或子类。因此,如果基类方法在throws子句中将异常指定为IOException,那么派生类方法可以将异常指定为FileNotFoundException、IOException但不指定exception
# 3 楼答案
顺序也必须相同,否则不会发生重写
# 4 楼答案
顺序很重要,因此具有不同顺序的相同参数的两个方法不会被视为具有相同的签名
例如,此示例不编译:
但是,参数的名称是不相关的。这很好:
# 5 楼答案
秩序很重要。如果订单不同,签名也不同。
public void foo(int x, Object y)
不能用重写public void foo(Object y, int x)
# 6 楼答案
该Java Language Specification称订单是重要的,但需要一些梳理来解释原因:
形式参数被指定为列表,因此“M和N的形式参数类型”要相同,它们必须是相同的列表,并且列表依赖于顺序
由于3中的对应关系是顺序相关的,因此类型参数的顺序也很重要
当处理Method Descriptors的字节码/JNI约定时,这一点变得更加明显