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'?
There can be a method that is not overridden but overloaded in the subclass. Here the subclass has two add() methods. The version which accepts int arguments(not overridden), and the overloaded method add() which accepts float arguments.
The concept of Overloading comes in play if and only if the functions are in the same scope or class. cz if this is the case of method overloading then for same method signature or same argument type the compiler gets confuse and must give compile time error . but in the above program in class B if you pass the same argument in same order then according to overloading it must give error but it is not happening u can check it i already have. It is the case of inheritance where through object reference if you call any method then the compiler will check it in child class ,if its not there then it will look into parent class that the above program is all about. hope this is helpfull.
In brief, yes. To override, you need to replicate the complete method signature, which includes the method name, parameters and return types. From the tutorial
You might want to consider the @Override annotation, which will trigger a compiler error if you don't successfully overrride a method.
In this particular instance, it perhaps looks like you don't need overriding so much as some solution including generics. So you could instantiate a class
a<Integer>
and a similar classa<Float>
I think in this particular case neither overloading nor overriding occurs, because return type must be same in case overloading and overriding, so neither static binding nor dynamic binding happens in this case. method overloading is not possible in case of different return type, because compiler can't figure that which method he need to call.
The method
add()
in class A is also available to class B by inheritance, therefore the method isoverloaded
in class by changing the data type fromint, int
tofloat, float
.Method add in class b is an overload of add in class a. Not an override. An override would just be a different implementation of the original add method.