Java中的方法重载和方法重写之间有什么区别?

以下是重载和覆盖之间的显着差异。

方法重载

  • 在方法重载中,一个类有两个或多个名称相同且参数不同的方法。

  • 在重载中,两种方法的返回类型都可能不同。

  • JVM在方法调用时根据传递给它的参数调用相应的方法。

示例

public class OverloadingExample {
   public void display(){
      System.out.println("Display method");
   }
   public void display(int a){
      System.out.println("Display method "+a);
   }
   public static void main(String args[]){
      OverloadingExample obj = new OverloadingExample();
      obj.display();
      obj.display(20);
   }
}

输出结果

Display method
Display method 20

方法覆盖

  • 在方法覆盖中,超类和子类具有名称相同的方法,包括参数。

  • 在重写中,返回类型也应该相同。

  • JVM根据用于调用方法的对象来调用相应的方法。

示例

class SuperClass{
   public static void sample(){
      System.out.println("Method of the super class");
   }
}
public class RuntimePolymorphism extends SuperClass {
   public static void sample(){
      System.out.println("Method of the sub class");
   }
   public static void main(String args[]){
      SuperClass obj1 = new RuntimePolymorphism();
      RuntimePolymorphism obj2 = new RuntimePolymorphism();
      
      obj1.sample();
      obj2.sample();
   }
}

输出结果

Method of the super class
Method of the sub class