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

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

问题描述

重载方法和覆盖方法有什么区别?谁能用例子解释一下?

解决方案

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

>

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

Method overriding 意味着具有两个具有相同参数但实现不同的方法.其中一个存在于父类中,而另一个存在于派生类或子类中.@Override 注释虽然不是必需的,但有助于强制正确覆盖方法在编译时.

class Parent {void foo(double d) {//做点什么}}类子扩展父{@覆盖void foo(double d){//这个方法被覆盖了.}}

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)

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天全站免登陆