I notice that in Java
, if you override a method in subclass, you can still call the overriden method declaced only in superclass. But in C++
, it will be hiden.
The Java code:
class Fish {
public void foo() {}
}
class Tuna extends Fish {
public void foo(int i) {}
}
public class Test{
public static void main(String[] args) {
Tuna t = new Tuna();
t.foo();
t.foo(1);
}
}
The C++ code:
class Fish {
public:
void foo() {}
};
class Tuna : public Fish {
public:
void foo(int i) {}
};
int main() {
Tuna t;
t.foo(1); // ok
t.foo(); // error
return 0;
}
I noticed some people present a few explanations in the Why does an overridden function in the derived class hide other overloads of the base class? . If it is true that
name hiding would prove to be a lesser evil
, why doJava
choose a more evil way?
Why do Java
and C++
behave different? Is it only becasue of the different name looking-up strategies between Java
and C++
?