首页 > 代码库 > CS 61B Lab5
CS 61B Lab5
其实我不太确定题目是否是这个意思,我就按照我的理解来答题,欢迎来讨论。
part one
a b c d 答案都在以下代码中
分析:array的情况和variable情况是一样的,除了代码中array 的cast有点点不一样。。。在compile过程中,array之间相互assign看的是static type,type一致或者是子类assign给了父类或者父类cast成子类之后assign给子类,这三种情况是可以通过compile time的。但是在run time过程中,看的是dynamic type,必须要一致,才能run。所以在d中最后,Dog type 的 twodogs 指向了 Teddy type,如此一来,在最后cast过后,就既能通过compile time,又能run起来了。
package lab5; public class Dog{ protected int legs; protected String voice; protected String name; Dog(){ legs = 4; voice = "wang"; name = "dog"; } /**************************************************************/ public static void main(String[] arg){ Dog onedog; Teddy oneTed = new Teddy(); onedog = oneTed; // oneTed = onedog; compile error oneTed = (Teddy)onedog; onedog = new Dog(); // oneTed = (Teddy)onedog; runtime error /**************************************************************/ Dog[] Twodogs; Teddy[] TwoTeddy=new Teddy[2]; TwoTeddy[0] = new Teddy(); TwoTeddy[1] = new Teddy(); Twodogs = TwoTeddy; // TwoTeddy = Twodogs;//compile error; TwoTeddy = (Teddy[])Twodogs; Twodogs = new Dog[2]; // TwoTeddy = (Teddy[])Twodogs; runtime error /**************************************************************/ Twodogs = new Teddy[2]; Twodogs = TwoTeddy; // TwoTeddy = Twodogs; compile error TwoTeddy = (Teddy[])Twodogs; // there is no run error or compile error } }
Part Two
(a) java will compile the result
package lab5; public interface Animals { public void Shout(); } package lab5; public class Dog{ protected int legs; protected String voice; protected String name; Dog(){ legs = 4; voice = "wang"; name = "dog"; } public void Shout(){ System.out.println(voice); } }
(b)NO
(c)NO
(d) Yes
Part Three
(a)Yes, there is no difference.
(bc) the situation is like this below.
Part Four
(a) call the subclass method
(b) run time error
(c)课上讲过的方法 用super调用superclass method
CS 61B Lab5
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。