Destructor
Destructor

Reputation: 14438

Why overloading works with inheritance in Java?

We know that overloading doesn't work for derived classes in C++. But why this behaviour is different in java? means why overloading works for derived classes in java ? Consider below example from the FAQ's of Dr. Stroustrup

#include <iostream>
using namespace std;
class Base
{
public:
    int f(int i)
    {
        cout << "f(int): ";
        return i+3;
    }
};
class Derived : public Base
{
public:
    double f(double d)
    {
        cout << "f(double): ";
        return d+3.3;
    }
};
int main()
{
    Derived* dp = new Derived;
    cout << dp->f(3) << '\n';
    cout << dp->f(3.3) << '\n';
    delete dp;
    return 0;
}

The output of this program is:

f(double): 6.3

f(double): 6.6

Instead of the supposed output:

f(int): 6

f(double): 6.6

But if we do this program in java then output is different.

class Base
{
    public int f(int i)
    {
        System.out.print("f (int): ");
        return i+3;
    }
}
class Derived extends Base
{
    public double f(double i)
    {
        System.out.print("f (double) : ");
        return i + 3.3;
    }
}
class Test
{
    public static void main(String args[])
    {
        Derived obj = new Derived();
        System.out.println(obj.f(3));
        System.out.println(obj.f(3.3));
    }
}

Upvotes: 1

Views: 122

Answers (2)

masoud
masoud

Reputation: 56479

You've said that "We know that overloading doesn't work for derived classes in C++".

It is not true or an accurate sentence. You can overload across base and derived classes in C++. Just need to using the parent's method into the derived class to un-hide that method.

class Derived : public Base
{
public:

    using Base::f;
    ^^^^^^^^^^^^^^

    double f(double d) { ... }
};

In Java overloaded (same name) method in the derived class doesn't hide its parent method and you don't need to explicitly bring it from the parent's method.

Upvotes: 7

NPE
NPE

Reputation: 500307

It works because the Java Language Specification explicitly permits it in §8.4.9. Overloading:

If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.

Also see §15.12.2. Compile-Time Step 2: Determine Method Signature.

Upvotes: 7

Related Questions