similar in Java, you are assigning object references, for example class B {...} class D extends B {...}D d = new D(); B b = d; //now b and d both point to the same instance, or same memoryYou can only assign a child class' instance to a parent class' variable, otherwise, explicit casting is needed
pengji说得没错,其实这些东西书本上都有,你就不能自己认真的看看书么?
Java中的对象直接付值其实是传递引用。 即: B.setX(2); A=B; B.setX(1); int i=A.getX(); 结果是i=1。
哦!这不是和C++里的一样吗? 我记住了! 那这样可不可以呢? B b = new B(); D d = b;//D d = (D)b
class B {...}
class D extends B {...}D d = new D();
B b = d;
//now b and d both point to the same instance, or same memoryYou can only assign a child class' instance to a parent class' variable, otherwise, explicit casting is needed
即:
B.setX(2);
A=B;
B.setX(1);
int i=A.getX();
结果是i=1。
我记住了!
那这样可不可以呢?
B b = new B();
D d = b;//D d = (D)b
要是想再另开一块空间的话(也就是复制一份),那就用clone()方法即可。
D d = b;//D d = (D)b
这段代码要依情况而定。如果B是D的子类,那么没有问题。
否则,很可能连编译的时候都通不过。