首页 > 代码库 > 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