下面這段代碼的輸出結(jié)果是什么?
public class Test { public static void main(String[] args) { new Circle(); }} class Draw { public Draw(String type) { System.out.println(type+" draw constructor"); }} class Shape { private Draw draw = new Draw("shape"); public Shape(){ System.out.println("shape constructor"); }} class Circle extends Shape { private Draw draw = new Draw("circle"); public Circle() { System.out.println("circle constructor"); }}運(yùn)行結(jié)果shape draw constructorshape constructorcircle draw constructorcircle constructor
父類(lèi)的構(gòu)造器調(diào)用以及初始化過(guò)程一定在子類(lèi)的前面。
由于Circle類(lèi)的父類(lèi)是Shape類(lèi),所以Shape類(lèi)先進(jìn)行初始化,然后再執(zhí)行Shape類(lèi)的構(gòu)造器。接著才是對(duì)子類(lèi)Circle進(jìn)行初始化,最后執(zhí)行Circle的構(gòu)造器。
2.下面這段代碼的輸出結(jié)果是什么?
public class Test { public static void main(String[] args) { Shape shape = new Circle(); System.out.println(shape.name); shape.printType(); shape.printName(); }} class Shape { public String name = "shape"; public Shape(){ System.out.println("shape constructor"); } public void printType() { System.out.println("this is shape"); } public static void printName() { System.out.println("shape"); }} class Circle extends Shape { public String name = "circle"; public Circle() { System.out.println("circle constructor"); } public void printType() { System.out.println("this is circle"); } public static void printName() { System.out.println("circle"); }}運(yùn)行結(jié)果shape constructorcircle constructorshapethis is circleshape
1.對(duì)于這個(gè)例子,靜態(tài)綁定的過(guò)程是:java文件編譯時(shí),編譯器檢查出引用shape的靜態(tài)類(lèi)型是Shape類(lèi),由于將printName()方法和父類(lèi)Father關(guān)聯(lián)起來(lái)。也就是說(shuō),程序運(yùn)行前編譯器是無(wú)法檢查出引用shape的動(dòng)態(tài)類(lèi)型的,所以會(huì)直接調(diào)用靜態(tài)類(lèi)型中對(duì)應(yīng)的方法。
2.覆蓋只針對(duì)非靜態(tài)方法,而隱藏是針對(duì)成員變量和靜態(tài)方法的。
3.覆蓋和隱藏之間的區(qū)別是:覆蓋受RTTI約束的,而隱藏卻不受該約束。也就是說(shuō)只有覆蓋方法才會(huì)進(jìn)行動(dòng)態(tài)綁定,而隱藏是不會(huì)發(fā)生動(dòng)態(tài)綁定的。
以上就是長(zhǎng)沙一度軟件培訓(xùn)java培訓(xùn)機(jī)構(gòu)的小編針對(duì)“Java面試題必知,常見(jiàn)Java繼承面試題”的內(nèi)容進(jìn)行的回答,希望對(duì)大家有所幫助,如有疑問(wèn),請(qǐng)?jiān)诰€咨詢(xún),有專(zhuān)業(yè)老師隨時(shí)為你服務(wù)。
Java面試題