作为初学者尝试多态性。我想我正在尝试不同语言的相同代码,但结果不一样:
C++
#include <iostream>
using namespace std;
class A {
public:
void whereami() {
cout << "You're in A" << endl;
}
};
class B : public A {
public:
void whereami() {
cout << "You're in B" << endl;
}
};
int main(int argc, char** argv) {
A a;
B b;
a.whereami();
b.whereami();
A* c = new B();
c->whereami();
return 0;
}
结果:
You're in A
You're in B
You're in A
Java:
public class B extends A{
void whereami() {
System.out.println("You're in B");
}
}
//and same for A without extends
//...
public static void main(String[] args) {
A a = new A();
a.whereami();
B b = new B();
b.whereami();
A c = new B();
c.whereami();
}
结果:
You're in A
You're in B
You're in B
不确定是我做错了什么,还是这与语言本身有关?
最佳答案
您需要阅读 C++ 的 virtual
关键字。如果没有该限定符,您所拥有的就是对象中的成员函数。它们不遵循多态性(动态绑定(bind))规则。使用 virtual
限定符,您可以获得使用动态绑定(bind)的方法。在 Java 中,所有实例函数都是方法。你总是会得到多态性。
关于java - 多态性? C++ 与 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34445553/