管理员
- 积分
- 77120
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2009-5-28
- 最后登录
- 1970-1-1
|
求讨论,我不确定我答案是对的
http://www.cs.berkeley.edu/~jrs/61b/lab/lab5/readme
((Superclass) subclassvariable).method();
我以为可以调用Super class的方法,但是居然不是的。。。为啥?
some code here, 求能人给看看啊啊啊
这个例子里面,没有什么办法能把Array of a superClass cast 成为 Array of subClass,我漏掉了什么吗?
- // Part I: Assignments and Casting (1 point)
- // ------------------------------------------
- // Let Y be a subclass of X, and let y and x be variables of classes Y and X
- // respectively. From lecture, you know that the assignment "x = y" is valid, but
- // the assignment "y = (Y) x" requires a cast to compile, and will cause a
- // run-time error if x references an object that isn't a Y.
- // What about arrays of objects? Suppose xa is an array of X's, and ya is an
- // array of Y's.
- class X{ //Animal
- protected int a = 1;
- public int aa(){return (1);}
- }
- class Y extends X{ //Dog
- protected int a = 2;
- public int aa(){return(2);}
- }
- class Z extends X{ //Cat
- protected int a = 3;
- public int aa(){return(3);}
- }
- class testClass{
- public static void main(String[] args){
- X x = new X();
- Y y = new Y();
- x = y;
- y = (Y) x;
- X[] xa = new X[5];
- Y[] ya = new Y[3];
- // (a) At compile-time, can we assign xa to ya, and vice versa? When is a cast
- // required?
- // can assign Dog to Animal, but not vice versa, without casting
- xa = ya;
- X[] xa2 = new X[2];
- Y[] ya2 = new Y[3];
- // (b) At run-time, if ya references an array of Y's, can we assign it to xa?
- // Can we then assign it back from xa to ya?
- // Yes can assign Array of Dogs to Animals, then assign back is also ok
- // ya2 = (Y[]) xa2; // can compile, run time error, can't assign animals as dogs.
- xa2[0] = new Y();
- xa2[1] = new Y();
- // ya2 = (Y[]) xa2; // still doesn't work, same run time error
- xa2 = ya2;
- X[] za = new X[2]; // array of animals
- // za[0] = new Z(); // this can be non assigned
- za[1] = new Z();
- // (c) If xa references an array of X's (that are not Y's), can we assign it to
- // ya? Can we then assign it back from ya to xa? Does it make a difference
- // if the array of type X[] references objects that are all of class Y? Why
- // do you think this is the case?
- // ya = (y[]) za; // run time error!! can not cast cats to dogs
- za = new X[2];
- za[0]=new Y();
- za[1]=new Y();
- // ya = (Y[]) za;// run time error!! can not cast cats to dogs
- }
- }
复制代码 |
|