Java重写和重载的区别

157 阅读2分钟

什么是重载

重载发生在同一个类中(或者是父类和子类之间),特点是方法的参数个数不同;顺序不同;类型不同;当仅仅只有返回参数不同时,不会构成重载,会发生编译错误。

需要注意的是,当我们传入重载方法的参数类型“小于”形参的数据类型时,会发生自动转换。

  • 假设传入的参数是byte,当重载方法形参中有short时,调用形参为short的重载方法,当有int时,调用重载方法为int的方法,以此类推
  • 假设传入的参数是short,和byte的情况一样
  • 假设传入的参数是char,那么如果重载方法形参中有short和int同时存在时,char会升级成为int 测试如下:
public class OverLoadMethod {

    void print(String s) {
        System.out.println(s);
    }

    void f1(int x){
        print("f1(int)");
    }

    void f1(short x){
        print("f1(short)");
    }
    void f1(byte x){
        print("f1(byte)");
    }
    void f1(char x){
        print("f1(char)");
    }
    void f1(long x){
        print("f1(long)");
    }
    void f1(float x){
        print("f1(float)");
    }
    void f1(double x){
        print("f1(double)");
    }

    void f2(short x) {
        print("f2(short)");
    }
    void f2(int x) {
        print("f2(int)");
    }
    void f2(long x) {
        print("f2(long)");
    }
    void f2(float x) {
        print("f2(float)");
    }

    void f3(long x) {
        print("f3(long x)");
    }
    void f3(float x) {
        print("f3(float x)");
    }
    void f3(double x) {
        print("f3(double x)");
    }

    void f4(float x) {
        print("f3(float x)");
    }
    void f4(double x) {
        print("f3(double x)");
    }

    void testInt(){
        int x = 1;
        f1(x);f2(x);f3(x);f4(x);
    }

    void testChar() {
        char x = 'x';
        f1(x);f2(x);f3(x);f4(x);
    }

    void testShort() {
        short s = 1;
        f1(s);f2(s);f3(s);f4(s);
    }

    void testByte() {
        byte b = 1;
        f1(b);f2(b);f3(b);f4(b);
    }

    public static void main(String[] args) {
        new OverLoadMethod().testInt();
        new OverLoadMethod().testChar();
        new OverLoadMethod().testShort();
        new OverLoadMethod().testByte();
    }

}

结果如下:

image.png

什么是重写

  1. 重写发生在运行期,是子类对父类方法的扩展
  2. 重写的方法的返回值必须比父类的方法的返回值类型更小或者相等,抛出的异常只能比父类的更小或者相等,权限修饰符不能比父类的更严格
  3. 构造方法不能重写
  4. 如果方法时private或者是final修饰的,不能被重写。如果是static修饰的,不存在重写的说法,这是属于类的方法,在子类中可以定义和父类一模一样的static方法,不收上述第2条的条件限制。