Given:



class Star {

    public void doStuff() {
        System.out.println("Twinkling Star");
    }
}

interface Universe {

    public void doStuff();
}

class Sun extends Star implements Universe {

    public void doStuff() {
        System.out.println("Shining Sun");
    }
}

public class Bob {

    public static void main(String[] args) {
        Sun obj2 = new Sun();
        Star obj3 = obj2;
        ((Sun) obj3).doStuff();
        ((Star) obj2).doStuff();
        ((Universe) obj2).doStuff();
    }
}

What is the result?

A.

Shining Sun
Shining Sun
Shining Sun

B.

Shining Sun
Twinkling Star
Shining Sun

C. Compilation fails
D. A ClassCastException is thrown at runtime

題解

程式第23行實體化出了一個Sun物件,接著將他向上轉型並呼叫其doStuff方法。由於Sun類別有覆寫(override)doStuff方法,因此不論轉成哪個型態都會去呼叫到第15行的doStuff方法。