方法重载和覆盖有什么区别? [英] What is the difference between method overloading and overriding?

查看:785
本文介绍了方法重载和覆盖有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重载方法和覆盖方法有什么区别?任何人都可以用一个例子来解释它吗?

What is the difference between overloading a method and overriding a method? Can anyone explain it with an example?

推荐答案

方法重载处理有两个或两个的概念同一个类中具有相同名称但不同参数的更多方法。

Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.

void foo(int a)
void foo(int a, float b)

方法覆盖表示有两个方法相同的参数,但不同的实现。其中一个将存在于父类中,而另一个将存在于派生类或子类中。 @Override 注释虽然不是必需的,但可以帮助强制执行适当的覆盖编译时的方法

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class Parent {
    void foo(double d) {
        // do something
    }
}

class Child extends Parent {

    @Override
    void foo(double d){
        // this method is overridden.  
    }
}

这篇关于方法重载和覆盖有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆