面向对象中的继承——重写方法的调用

今天在研究Android事件分发机制时候,遇到一个比较基础的问题,如下所示。

public class A {
	public static void main(String[] args) {
		C c = new C();
		c.show();
 	}
 	static class B {
 		void show() {
 			fun();
 		}
 		void fun() {
 			System.out.println("I am B and is father");
 		}
 	}
 	static class C {
 		void show() {
 			super.show();
 		}
 		void fun() {
 			System.out.println("I am C and is son");
 		}
 	}
}

程序的运行结果是:

I am C and is son

代码中,C继承B,并且重写了B的show和fun方法。C的show方法是直接调用父类B的show方法。从程序运行的结果来看,虽然C的show方法中是调用了父类的show方法,但并没有执行父类中的fun方法,而是执行了子类C中的fun方法。
所以继承关系重写方法的调用原则是:方法a在子类中被定义,则调用子类的方法a;若方法a中嵌套一个方法c,且c在子类中被定义,则调用子类的方法c,以此类推

猜你喜欢

转载自blog.csdn.net/codeIsGood/article/details/105395365