Java重写与重载:方法的‘改头换面’与‘改头换面’,必分清

In Java, method overriding and overloading are important features that beginners often confuse. Both allow methods to “change their appearance,” but their essential differences are significant. Today, we’ll distinguish between these two concepts in detail.

1. Method Overloading (Overload): “Shape-Shifting” with Different Parameters

Imagine you have a calculator that needs to handle addition for different types of numbers: adding two integers, two decimals, or even three integers. In this case, you can use the same method name but with different parameters—this is “overloading.”

Definition:

In the same class, methods with the same name but different parameter lists (different types, quantities, or order of parameters) are called method overloads.
Return types, access modifiers, and thrown exceptions can differ, but only the parameter list is used to distinguish overloading.

Example:

public class Calculator {
    // Overload 1: Add two integers
    public int add(int a, int b) {
        return a + b;
    }

    // Overload 2: Add two doubles (different parameter type)
    public double add(double a, double b) {
        return a + b;
    }

    // Overload 3: Add three integers (different parameter count)
    public int add(int a, int b, int c) {
        return a + b + c;
    }
}

When called, Java automatically matches the method based on the passed parameters:

Calculator calc = new Calculator();
int sum1 = calc.add(1, 2);       // Matches add(int, int)
double sum2 = calc.add(1.5, 2.5); // Matches add(double, double)
int sum3 = calc.add(1, 2, 3);     // Matches add(int, int, int)

Notes:

  • Only parameter lists matter—different return types do not count as overloading. For example:
  // Error! Same parameters, different return types → Compilation fails
  public int add(int a, int b) { return a + b; }
  public double add(int a, int b) { return a + b; } // Compilation error
  • Static methods can also be overloaded, e.g., public static void show() and public static void show(String msg).

2. Method Overriding (Override): “Upgraded Implementation”

When a subclass inherits from a parent class, it may need to modify the parent method’s implementation (e.g., changing the parent class’s “animal sound” method to “woof” for a dog subclass)—this is “overriding.”

Definition:

After a subclass inherits from a parent class, the subclass reimplements the parent class’s method. Requirements:
- Method name and parameter list must be identical (method signature must match exactly).
- Return type: The subclass’s return type must be a subclass of the parent’s return type (e.g., parent returns Object, subclass returns String).
- Access modifier: The subclass cannot restrict access more strictly than the parent (e.g., if the parent is public, the subclass cannot use private).
- Exception throwing: The subclass cannot throw a wider range of exceptions than the parent.

Example:

// Parent class: Animal
class Animal {
    public void bark() {
        System.out.println("Animal makes a sound");
    }
}

// Subclass: Dog (inherits from Animal)
class Dog extends Animal {
    // Override the parent class's bark() method
    @Override
    public void bark() {
        System.out.println("Woof!"); // New implementation
    }
}

When called, polymorphism prioritizes the subclass’s overridden method:

Animal animal = new Dog(); // Upcasting
animal.bark(); // Output: Woof!

Notes:

  • Parameter lists must be identical—otherwise, it’s overloading, not overriding. For example:
  class Dog extends Animal {
      // Error! Different parameters → Not overriding (new method)
      public void bark(String sound) { 
          System.out.println(sound);
      }
  }
  • Static methods cannot be overridden—they can only be “hidden.” For example, if the parent has static void bark(), the subclass using static void bark() will hide the parent method, not override it.

3. Overload vs Override: Quick Reference Table

Feature Method Overloading Method Overriding
Location Within the same class Between subclass and parent class
Parameter List Must differ (type, count, order) Must be exactly the same
Method Name Same Same
Inheritance Irrelevant to inheritance Depends on subclass inheriting
Return Type Can differ Subclass of parent’s return type
Core Purpose Provide multiple parameter handling in the same class Upgrade the parent method in the subclass

Summary: One-Sentence Clarification

  • Overload: Same class, “change parameters” (same name, different parameters).
  • Override: Subclass, “change implementation” (same name and parameters, return a more specific type).

Remember: Overload checks “parameters,” Override checks “inheritance”! Practice with examples to master this quickly.

Xiaoye