Function override-overload in Java

后端 未结 6 2134
庸人自扰
庸人自扰 2020-12-05 21:18

What is the difference between override and overload?

6条回答
  •  [愿得一人]
    2020-12-05 21:44

    • 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.

提交回复
热议问题