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'?
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
orDynamic binding
.It is Static Binding So, why?
Static Binding
Compile time
.private
,final
andstatic
methods and variables uses static binding and bonded by compiler.Dynamic Binding
Dynamic binding occurs during
Runtime
.Dynamic methods bonded during runtime based upon runtime object.
Dynamic binding uses Object to resolve binding.
But the important part is here
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.
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.
but for above code it will give compile time error for float arguments.
Hope it clears all doubts.
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.