java和C++中的上转型问题的区别

JAVA上转型问题,我想就是C++的同名覆盖。。。

由于现在在研究java.发现了在上转型问题上,两者确实存在一些比较大的区别,我想区别的来源主要是由于JAVA中使用的都是别名。如下例子说明了这个问题,应该看一下就知到什么回事了。

//java.code
//

public class ttest { public static void main (String[] args) { A aa=new A(); B bb=new B(); bb.x=10; bb.y=20; aa=bb; System.out.println("sum is "+aa.sum()); } } class A { int x; int y; int sum() { return x+y; } } class B extends A { int sum() { return 2*(x+y); } }

输出结果:sum is 60.

----------------------------------------------------------------------

而在C++中,我做了个类似的例子,

//C++ code
//

#include<iostream> using namespace std; class A { int x; int y; public: void setxy(int xx,int yy) { x=xx; y=yy; } void disp() { cout<<"here is class A's fun() /n"; } }; class B:public A { void disp() { cout<<"here is class B's fun() /n"; } }; void main() { A aa; B bb; bb.setxy(10,20); aa=bb; aa.disp(); }

 

输出结果:here is class A's fun( )

你可能感兴趣的:(java,C++,c,String,Class,fun)