我们可以在Java重写中更改方法签名吗?

不,在覆盖超类的方法时,我们需要确保两个方法都具有相同的名称,相同的参数和相同的返回类型,否则它们将被视为不同的方法。

简而言之,如果我们更改签名,则尝试执行超类的方法时,将无法覆盖超类的方法。

原因-如果更改签名,则这两种方法都被视为不同的方法,并且由于超类方法的副本在子类对象中可用,因此将执行该方法。

示例

class Super {
   void sample(int a, int b) {
      System.out.println("Method of the Super class");
   }
}
public class MethodOverriding extends Super {
   void sample(int a, float b) {
      System.out.println("Method of the Sub class");
   }
   public static void main(String args[]) {
      MethodOverriding obj = new MethodOverriding();
      obj.sample(20, 20);
   }
}

输出结果

Method of the Super class