更新時間:2020-08-05 15:47:43 來源:動力節點 瀏覽3336次
下面這段代碼的輸出結果是什么?
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");
}
}
運行結果
shape draw constructor
shape constructor
circle draw constructor
circle constructor
父類的構造器調用以及初始化過程一定在子類的前面。
由于Circle類的父類是Shape類,所以Shape類先進行初始化,然后再執行Shape類的構造器。接著才是對子類Circle進行初始化,最后執行Circle的構造器。
2.下面這段代碼的輸出結果是什么?
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");
}
}
運行結果
shape constructor
circle constructor
shape
this is circle
shape
1.對于這個例子,靜態綁定的過程是:java文件編譯時,編譯器檢查出引用shape的靜態類型是Shape類,由于將printName()方法和父類Father關聯起來。也就是說,程序運行前編譯器是無法檢查出引用shape的動態類型的,所以會直接調用靜態類型中對應的方法。
2.覆蓋只針對非靜態方法,而隱藏是針對成員變量和靜態方法的。
3.覆蓋和隱藏之間的區別是:覆蓋受RTTI約束的,而隱藏卻不受該約束。也就是說只有覆蓋方法才會進行動態綁定,而隱藏是不會發生動態綁定的。
以上就是動力節點java培訓機構的小編針對“Java面試題必知,常見Java繼承面試題”的內容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業老師隨時為你服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習