下面的例子可以:
(1) 深入理解java多态的机制。
(2) 为面向抽象编程提供基础。
(3) 理解设计模式

public class de1 {
	public static void main(String[] args) {
		A a1 = new A();
		A a2 = new B();
		B b = new B();
		C c = new C();
		D d = new D();
		System.out.println(a1.show(b));
		System.out.println(a1.show(c));
		System.out.println(a1.show(d));
		System.out.println(a2.show(b));
		System.out.println(a2.show(c));
		System.out.println(a2.show(d));
		System.out.println(b.show(b));
		System.out.println(b.show(c));
		System.out.println(b.show(d));
	}
}
class A {
	public String show(D obj) {
		return ("A and D");
	}
	public String show(A obj) {
		return ("A and A");
	}
}
class B extends A {
	public String show(B obj) {
		return ("B and B");
	}
	public String show(A obj) {
		return ("B and A");
	}
}
class C extends B {
}
class D extends B {
}

(4)运行结果:
A and A
A and A
A and D
B and A
B and A
A and D
B and B
B and B
A and D

实验结果分析:

先找子类的方法,如果子类对象没有该方法,向上查找父类中的方法,以此类推。方法中的obj对象也是这样运作的,当调用的方法obj对象不存在时,查找obj对象的父类,以此类推。实例化了一个带继承关系的类时,父类中的方法被调用后,由于子类重写了方法,所以最终调用的是子类的方法。