# 看題目是不是很繞,這個我也不知道怎么才能更簡單的表達了。。。
# 先看代碼:
public class Common { public static void main(String[] args) { Sub sub = new Sub(); sub.testSub(); } } class Parent { protected boolean test() { throw new RuntimeException(); } protected void testParent() { if (test()) { System.out.println(this.getClass().getName()); } } } class Sub extends Parent { public void testSub() { super.testParent(); } @Override public boolean test() { return true; } }
# 上面的代碼的輸出結果是:
com.qq.demo.common.Sub
# 大致流程是 main 中調用子類的 testSub()方法 -- testSub()方法中調用父類的testParent() 方法 -- testParent() 方法調用test()方法;需要注意的是test()方法在父類和子類中都存在,子類重寫了父類的test()方法;
