Is this Overloading, methods with same name in dif

2019-04-24 14:04发布

If I have the following code in Java:

class A {

    public int add(int a , int b) {
        return (a+b);
    }
}

class B extends A {
    public float add(float a , float b) {
        return (a+b);
}

In this particular case the sub-class isn't exactly overriding the base class's add function as they have different signatures and the concept of overloading occurs only if they are in the same scope. So, is the function add(float , float) in the sub-class B treated as an entirely new function and the concept of overloading and overriding is not applicable to it? And does it use 'Static binding' or 'Dynamic Binding'?

8条回答
2楼-- · 2019-04-24 14:28

I know it's late answer but i think it's important question need to be answered for beginners.

One key point in overloading is it works in inheritance.

Next is either it's Static binding or Dynamic binding.

It is Static Binding So, why?

Static Binding

  1. Static binding in Java occurs during Compile time.
  2. private, final and static methods and variables uses static binding and bonded by compiler.
  3. Static binding uses Type (class in Java) information for binding.

Dynamic Binding

  1. Dynamic binding occurs during Runtime.

  2. Dynamic methods bonded during runtime based upon runtime object.

  3. Dynamic binding uses Object to resolve binding.

But the important part is here

Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.

Java compiler determines correct version of the overloaded method to be executed at compile time based upon the type of argument used to call the method and parameters of the overloaded methods of both these classes receive the values of arguments used in call and executes the overloaded method.

B a=new B();
a.add(4, 5);
a.add(4.0f, 5.0f);

So if you will create reference of type B then it will search for proper argument type and for above code it will execute both methods.

A a=new B();
a.add(4, 5);
a.add(4.0f, 5.0f);

but for above code it will give compile time error for float arguments.

Hope it clears all doubts.

查看更多
Bombasti
3楼-- · 2019-04-24 14:32

In that case you are not overriding the method, since the signatures are different.

But there is overloading in class b, since you have two methods with the same name but different parameters (one if class a, and the other one in class b)

Hope it helps.

查看更多
登录 后发表回答