重载和重写的区别

重载和重写的区别

重载(Overload)

重载:在同一个类中,多个方法具有相同的方法名,但是方法的参数列表不同(参数类型、参数个数或顺序不同)。
重载是一个类中多态性的表现,调用相同方法名方法时,根据传递的参数来决定使用哪个方法,在编译时已经对方法进行绑定(编译时的多态性)

public class FunOverload {

    public static void main(String[] args) {

        FunOverload test = new FunOverload();
        int num1 = 1;
        int num2 = 2;
        long num3 = 3L;
        System.out.println(test.add(num1, num2));   //输出结果:3
        System.out.println(test.add(num1, num2, num2)); //输入结果:5
        System.out.println(test.add(num1, num3));   // 输入结果:4

    }

    public int add(int num1, int num2) {
        return num1 + num2;
    }

    public int add(int num1, long num2) {
        return num1 + num2;
    }

    public int add(int num1, int num2, int num3) {
        return num1 + num2 + num3;
    }

}

重写(Override)

重写:在子类继承父类时,子类定义的方法和父类中的方法具有相同的方法名,相同的参数列表和兼容的返回类型,又称为方法覆盖。
重写在子类与父类间呈现出多态性,当父类引用变量赋值为子类对象,并调用子类中的重写方法,此时在程序运行时会调用子类中经过重写的方法(方法的动态绑定),而不是父类中定义的方法,在调用时才对方法进行绑定(运行时的多态性)
注:子类中不能重写父类中的final方法;
子类中必须重写父类中的abstract方法;

public class Father {

    public static void main(String[] args) {

        Father children = new Children();
        Father father = new Father();
        children.sayHello();    //输出:Class Children say: Hello
        children.saySon();      //输出:Class Father say: Come on, baby
        father.sayHello();      //输出:Class Father say: Hello
        father.saySon();        //输出:Class Father say: Come on, baby

    }

    public void sayHello() {
        System.out.println("Class Father say: Hello");
    }

    public void saySon() {
        System.out.printlin("Class Father say: Come on, baby");
    }

}

public class Children extends Father {

    public void sayHello() {
        System.out.println("Class Children say: Hello");
    }

}

重载和重写的区别

方法的重载和重写都是多态性的实现,区别在于前者实现的是编译时的多态性,而后者实现的是运行时的多态性。
重载发生在一个类中,同名的方法如果有不同的参数列表(参数类型不同、参数个数不同或者二者都不同)则视为重载。重载对返回类型没有特殊的要求,不能根据返回类型进行区分;
重写发生在子类与父类之间,子类重写父类方法时需要有相同的参数列表,有兼容的返回类型,比父类方法更好访问,不能比父类方法声明更多的异常(里氏代换原则)。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值