SCJP(OCPJP) 考古題解析 第16題

Given:

class Atom {
    Atom() {System.out.print("atom ");}
}
class Rock extends Atom {
    Rock(String type) {System.out.print(type);}
}
public class Mountain extends Rock {
    Mountain() {
        super("granite ");
        new Rock("granite ");
    }
    public static void main(String[] a) {new Mountain();}
}

What is the result?


A. Compilation fails.
B. atom granite
C. granite granite
D. atom granite granite
E. An exception is thrown at runtime.
F. atom granite atom granite


答案:


解析:


子代的建構子在運作之前

必定會先運行父代的建構子

父代的建構子又會運行父代的父代的建構子

直到最上層Object 代為止...



若建構子中未寫this或super的呼叫敘述

編譯器會在建構子的首行加上super()

以此例來說

建立Mountain物件時

會先叫用super("granite")

呼叫其父類別Rock的建構子

Rock建構子會再呼叫其父類別Atom的建構子

因此會照順序印出atomgraniteatomgranite




0 意見:

張貼留言