What is the result?
abstract class A1 {
public abstract void m1();
public void m2() {
System.out.println("Green");
}
}
abstract class A2 extends A1 {
public abstract void m3();
public void m1() {
System.out.println("Cyan");
}
public void m2() {
System.out.println("Blue");
}
}
public class A3 extends A2 {
public void m1() {
System.out.println("Yellow");
}
public void m2() {
System.out.println("Pink");
}
public void m3() {
System.out.println("Red");
}
public static void main(String[] args) {
A2 tp = new A3();
tp.m1();
tp.m2();
tp.m3();
}
}
What is the result?
A.
Yellow
Pink
Red
Pink
Red
B.
Cyan
Blue
Red
Blue
Red
C.
Cyan
Green
Red
Green
Red
D. Compilation Fails
題解
tp變數所參考到的是A3類別的物件實體,A3類別覆寫了m1, m2, m3方法。
程式第39行會執行A3類別覆寫的m1方法,輸出「Yellow」。
程式第40行會執行A3類別覆寫的m2方法,輸出「Pink」。
程式第41行會執行A3類別覆寫的m2方法,輸出「Red」。