📜  Java方法重载和方法覆盖的区别

📅  最后修改于: 2021-09-15 01:15:42             🧑  作者: Mango

方法重载:
方法重载是一种编译时多态性。在方法重载中,多个方法在类中共享相同的方法名称但具有不同的签名。在方法重载中,返回类型可以相同也可以不相同,但是我们必须改变参数,因为在Java,我们不能通过改变方法的返回类型来实现方法重载。
方法重载示例:

class MethodOverloadingEx{  
   static int add(int a, int b){return a+b;}  
   static int add(int a, int b, int c){return a+b+c;}  
 
    public static void main(String args[]) {
      System.out.println(add(4, 6));
      System.out.println(add(4, 6, 7));
    }
} 

输出:

//Here, add with two parameter method runs
10 

// While here, add with three parameter method runs 
17 

方法覆盖:
方法覆盖是一种运行时多态性。在方法覆盖中,派生类提供基类或父类已经提供的方法的具体实现。在方法覆盖中,返回类型必须相同或协变(返回类型可以在与派生类相同的方向上变化)。

方法覆盖示例:

class Animal{  
      void eat(){System.out.println("eating.");}  
      }  
    class Dog extends Animal{  
    void eat(){System.out.println("Dog is eating.");}  
     }  
   class MethodOverridingEx{  
    public static void main(String args[]) {
      Dog d1=new Dog();
      Animal a1=new Animal();
      d1.eat();
      a1.eat();
    }
} 

输出:

// Derived class method eat() runs
Dog is eating

// Base class method eat() runs
eating 

/* 在这里,我们可以看到在派生类名称Dog中覆盖了一个方法eat(),该类名称已经由基类名称Animal 提供
当我们创建类 Dog 的实例并调用eat() 方法时,我们看到只有派生类的eat() 方法运行而不是基类方法eat() 并且当我们创建类Animal 的实例并调用eat() 时方法,我们看到只有基类eat() 方法运行而不是派生类方法eat()。

因此,很明显,在方法覆盖中,方法绑定到运行时的实例,这由JVM决定。这就是为什么它被称为运行时多态性*/

Java方法重载和方法覆盖的区别:

S.NO Method Overloading Method Overriding
1. Method overloading is a compile time polymorphism. Method overriding is a run time polymorphism.
2. It help to rise the readability of the program. While it is used to grant the specific implementation of the method which is already provided by its parent class or super class.
3. It is occur within the class. While it is performed in two classes with inheritance relationship.
4. Method overloading may or may not require inheritance. While method overriding always needs inheritance.
5. In this, methods must have same name and different signature. While in this, methods must have same name and same signature.
6. In method overloading, return type can or can not be be same, but we must have to change the parameter. While in this, return type must be same or co-variant.