重载和重写的区别???

1、 重载 :(overload)

在这里插入图片描述

(1)个数不同
在这里插入图片描述

public class OverLoad {
    
    
    public static int add (int a,int b) {
    
    
        return a + b;
    }
    public static int add (int a,int b,int c) {
    
    
        return a + b + c;
    }
    public static void main(String[] args) {
    
    
        int a = 10;
        int b = 20;
        System.out.println(add(a,b));
        int c = 12;
        System.out.println(add(a,b,c));
    }
}

(2) 类型不同

在这里插入图片描述

public class OverLoad {
    
    
    public static int add (int a,int b) {
    
    
        return a + b;
    }
    public static double add (double x,double y) {
    
    
        return x + y;
    }
    public static void main(String[] args) {
    
    
        int a = 10;
        int b = 20;
        System.out.println(add(a,b));
        double c = 12.5;
        double d = 13.5;
        System.out.println(add(c,d));
    }
}

(3) 顺序不同
在这里插入图片描述

public class OverLoad {
    
    
    public static double add (double a,int b) {
    
    
        return a + b;
    }
    public static double add (int x,double y) {
    
    
        return x + y;
    }
    public static void main(String[] args) {
    
    
        double a = 10.7;
        int b = 20;
        System.out.println(add(a,b));
        int c = 12;
        double d = 13.5;
        System.out.println(add(c,d));
    }
}

2、重写 : (override)

(1)方法名相同
(2)参数列表相同(参数的个数,参数的类型)
(3)返回值也要相同

但是有几点需要注意:
(1)要重写的方法,不能是 private 所修饰的
(2)被 finale 所修饰的方法,不能被重写
(3)需要重写方法的,访问修饰限定符,子类的访问修饰限定符一定要大于或者等于父类的访问修饰限定符

猜你喜欢

转载自blog.csdn.net/qq_45658339/article/details/108822052
今日推荐