Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this Overloading, methods with same name in different classes and different signature?

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'?

like image 519
Genocide_Hoax Avatar asked Mar 08 '13 10:03

Genocide_Hoax


4 Answers

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.

like image 68
Breavyn Avatar answered Nov 03 '22 19:11

Breavyn


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

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

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 class a<Float>

like image 24
Brian Agnew Avatar answered Nov 03 '22 18:11

Brian Agnew


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.

like image 30
Cacho Santa Avatar answered Nov 03 '22 20:11

Cacho Santa


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.

like image 1
Prateek Sharma Avatar answered Nov 03 '22 18:11

Prateek Sharma