Java中的函数覆盖 - 重载 [英] Function override-overload in Java

查看:130
本文介绍了Java中的函数覆盖 - 重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

覆盖和重载有什么区别?

解决方案


  • 重载:拣货编译时基于指定参数的数量和类型的方法签名


  • 覆盖:选择方法实现在执行时根据目标对象的实际类型(而不是表达式的编译时类型)




例如:

  class Base 
{
void foo(int x)
{
System.out.println(Base.foo(int));
}

void foo(double d)
{
System.out.println(Base.foo(double));
}
}

class子扩展基数
{
@Override void foo(int x)
{
系统。通过out.println( Child.foo(INT));
}
}

...

基数b =新子项();
b.foo(10); //打印Child.foo(int)
b.foo(5.0); //打印Base.foo(double)

这两个调用都是重载的示例。有两种方法称为 foo ,编译器确定要调用的签名。



第一个调用是一个例子覆盖。编译器选择签名foo(int),但在执行时,目标对象的类型确定要使用的实现应该是 Child 中的实现。 / p>

What is the difference between override and overload?

解决方案

  • Overloading: picking a method signature at compile time based on the number and type of the arguments specified

  • Overriding: picking a method implementation at execution time based on the actual type of the target object (as opposed to the compile-time type of the expression)

For example:

class Base
{
    void foo(int x)
    {
        System.out.println("Base.foo(int)");
    }

    void foo(double d)
    {
        System.out.println("Base.foo(double)");
    }
}

class Child extends Base
{
    @Override void foo (int x)
    {
        System.out.println("Child.foo(int)");
    }
}

...

Base b = new Child();
b.foo(10); // Prints Child.foo(int)
b.foo(5.0); // Prints Base.foo(double)

Both calls are examples of overloading. There are two methods called foo, and the compiler determines which signature to call.

The first call is an example of overriding. The compiler picks the signature "foo(int)" but then at execution time, the type of the target object determines that the implementation to use should be the one in Child.

这篇关于Java中的函数覆盖 - 重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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