Java Override/Overload

方法重写与重载的区别、重写规则与 @Override 注解。

Intermediate
Key Points重写发生在父子类之间、签名必须相同;重载发生在同类中、参数列表不同。重写不能缩小访问权限。

重写(Override)

A subclass method with the same name and parameters overrides the parent's; calls dispatch to the child version. The @Override annotation lets the compiler verify the signature.

Java
class Animal {
    void move() {
        System.out.println("animal moves");
    }
}

class Dog extends Animal {
    @Override
    void move() {
        System.out.println("dog runs");
    }
}

public class OverrideDemo {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.move();
    }
}
Output
dog runs

方法的重写规则

An override must keep the same name and parameters, return the same type or a subtype (covariant return), not narrow visibility, not widen checked exceptions, and cannot target final, static or private methods.

RuleAllowed?
Same name and parametersRequired
Narrower access (public to private)Forbidden
Wider checked exceptionForbidden
Covariant return typeAllowed
Override a final methodForbidden

重载(Overload)

Overloading means the same name with different parameters in one class; the compiler picks by argument types at compile time (static binding). Overriding is resolved at runtime from the object's real type (dynamic binding).

Java
public class OverloadDemo {
    static void show(int a) {
        System.out.println("int: " + a);
    }

    static void show(String s) {
        System.out.println("String: " + s);
    }

    static void show(int a, int b) {
        System.out.println("two ints: " + a + "," + b);
    }

    public static void main(String[] args) {
        show(1);
        show("x");
        show(1, 2);
    }
}
Output
int: 1
String: x
two ints: 1,2

重写与重载的区别

In one line: overriding rewrites a parent's behaviour in a subclass; overloading provides several parameter variants of one operation. The first is runtime polymorphism, the second compile-time selection.

AspectOverrideOverload
WhereParent and child classSame class
SignatureMust be identicalMust differ
BindingRuntimeCompile time
PolymorphismYesNo

Friends & Partners