今天去一家外企的面試題.....

ggggggg發表於2008-05-25
首先問了我這麼一段程式,讓我寫出它的輸出,當然,這個沒啥問題

// codes start
class base{//a base class

// constructor
public base(){
System.out.println("base class construct");
}
// perform
public void perform(){
System.out.println("base class perform");
}

}


class subbase extends base{// derive from base

// constructor
public subbase(){
System.out.println("sub class construct");
}
// perform
public void perform(){
System.out.println("sub class perform");
}

}

public class casting{// test casting class
// constructor
public casting(){
System.out.println("begin casting test");
}

public static void main(String args[]){
base father = new base();
subbase son = new subbase();



father = (base)son; // <1>
father.perform();

son = (subbase)father; // <2>
son.perform();

father = (base)((subbase)father); // <3>
father.perform();
}
}

// codes end

************************************************** *
and the execution result is:
// begin
base class construct
base class construct
sub class construct

sub class perform // <a>
sub class perform // <b>
sub class perform // <c>
// end

************************************************** **

然後就寫了,然後他問為啥,俺就答啊,無非就是一個引用的問題嘛,他老人家還挺高興,無奈笑裡藏刀,馬上又問了一個問題,
((base)new subbase()).perform();
這個語句沒有啥引用了吧,你說說為啥也輸出 sub class perform 啊?

我當時傻眼了,現在還傻呢

也是 new 關鍵字就是產生物件用的,莫非是java虛擬機器內部的事情?

請諸位幫忙給個解答,然後我就找塊最大的豆腐撞死算了.........

相關文章