方法重载和方法重写的区别
方法重载:在同一个类中定义多个具有相同名称但参数列表不同的方法。编译器根据调用时传递的参数类型和数量来决定调用哪个方法。
方法重写:在子类中重新定义父类中的方法,要求方法名、参数列表和返回类型(或其子类型)完全一致。访问修饰符不能比父类方法更严格,且不能抛出比父类方法更宽泛的异常。方法重写是实现多态的关键机制之一,它允许子类提供与父类方法不同的实现。
| 特征 | 方法重载 | 方法重写 |
|---|---|---|
| 位置 | 同一个类中 | 继承关系的类中 |
| 方法名 | 相同 | 相同 |
| 参数列表 | 必须不同 | 必须相同 |
| 返回类型 | 可以不同 | 相同或子类型 |
| 访问修饰符 | 可以不同 | 不能更严格 |
| 异常 | 无限制 | 不能抛出更宽泛异常 |
| 绑定 | 编译时绑定(静态绑定) | 运行时绑定(动态绑定) |
方法重载
public class MethodOverloadingExample {
// 方法重载:参数列表不同
public void display(int num) {
System.out.println("Displaying integer: " + num);
}
public void display(String str) {
System.out.println("Displaying string: " + str);
}
public static void main(String[] args) {
MethodOverloadingExample example = new MethodOverloadingExample();
example.display(10); // 调用 int 参数的方法
example.display("Hello"); // 调用 String 参数的方法
}
}
方法重写
规则:不能重写声明为final和static的方法。当方法被声明为final时,Java语言规范的强制规定不能被重写,编译器会将其内联优化,提高执行效率。当方法被static修饰时(可以写,会有警告,但是无效),因为被static方法就会在编译时绑定(静态绑定),而不是运行时绑定,所以被static修饰的方法属于类的本身,而非类的实例,在运行时的调用也只能调用到编译时候的方法。
class ParentClass {
// 父类方法
public void show() {
System.out.println("Parent's show method");
}
}
class ChildClass extends ParentClass {
// 方法重写:必须有相同的参数列表和返回类型,访问修饰符不能更严格
@Override
public void show() {
System.out.println("Child's show method");
}
public static void main(String[] args) {
ParentClass obj1 = new ParentClass();
ParentClass obj2 = new ChildClass();
obj1.show(); // 输出: Parent's show method
obj2.show(); // 输出: Child's show method (运行时绑定)
}
}
class Animal {
public static void type() {
System.out.println("Animal");
}
}
class Dog extends Animal {
public static void type() {
System.out.println("Dog");
}
}
public class Test {
public static void main(String[] args) {
Animal animal = new Dog();
animal.type(); // 输出 "Animal",而不是 "Dog"
// 实际上应该通过类名调用
Animal.type(); // 输出 "Animal"
Dog.type(); // 输出 "Dog"
}
}

浙公网安备 33010602011771号