重载和重写的区别总结

目录

1. 什么是重载

2. 什么是重写

3. 二者的区别


1. 什么是重载

重载(overload),它是指我们可以定义一些名称相同的方法,通过定义不同的输入参数来区分这些方法,然后再调用时,VM就会根据不同的参数样式,来选择合适的方法执行。

重载最常见于java的编写过程中,是面向对象程序设计(Object Oriented Programming)的特性之一。

 重载的规则:

  • 方法名相同;
  • 方法的参数不同(包括参数个数或者参数类型);
  • 方法的返回值类型不影响重载。

代码示例:

   public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int ret = add(a, b);
        System.out.println("ret = " + ret);
        double a2 = 10.5;
        double b2 = 20.5;
        double ret2 = add(a2, b2);
        System.out.println("ret2 = " + ret2);
        double a3 = 10.5;
        double b3 = 10.5;
        double c3 = 20.5;
        double ret3 = add(a3, b3, c3);
        System.out.println("ret3 = " + ret3);
    }

    public static int add(int x, int y) {
        return x + y;
    }

    public static double add(double x, double y) {
        return x + y;
    }

    public static double add(double x, double y, double z) {
        return x + y + z;
    }

2. 什么是重写

在 Java 中子类可继承父类中的方法,而不需要重新编写相同的方法。但有时子类并不想原封不动地继承父类的方法,而是想作一定的修改,这就需要采用方法的重写。方法重写又称方法覆写,方法覆盖。

重写的规则:

  • 重写的方法方法名、参数列表必须一致,方法返回值也要一致(除了向上转型);
  • 重写方法时子类的方法的访问权限不能低于父类的方法访问权限;
  • 普通方法可以重写,但是 static 修饰的静态方法不能重写;
  • final 修饰的方法不能被重写。

访问权限由大到小:public > protected > default > private

代码示例:

public class Animal {
    public void eat(String food) {
        System.out.printf("动物会吃");
    }
}

public class Bird extends Animal {
    @Override
    public void eat(String food) {
        super.eat(food);
    }

    public static void main(String[] args) {
        Bird bird = new Bird();
        bird.eat("虫子");
    }
}

ps:推荐在代码中进行重写方法时显式加上 @Override 注解 。

运行结果:

3. 二者的区别

  • 重载是一个类中的方法进行重载;而重写和继承有关,是子类重写父类中的方法。
  • 重载只要求方法名称相同,参数类型及个数不同;重写要求方法名称,参数类型及个数,返回值类型都要相同。
  • 重载对于方法的访问权限没有要求,而重写则要求子类重写的方法不能低于父类被重写方法的访问权限。

 

猜你喜欢

转载自blog.csdn.net/AlinaQ05/article/details/125624502