publicclass test {publicstaticvoidmain(String[] args){A a1 =newA();A a2 =newB();B b =newB();C c =newC();D d =newD();//a1调用 A 里面的show方法System.out.println(a1.show(b));//B是D的父类,父亲不能放到孩子里 -- (A obj) "A and A"System.out.println(a1.show(c));//C和D 是兄弟关系 不能放到D里,放不下 --(A obj) "A and A"System.out.println(a1.show(d))// D类型可以放到D里边 --(D obj) "A and D"//a2 可以使用A 里面的show方法,也可以使用子类重写的父类的方法// public String show(D obj) {// return "A and D";// }public String show(A obj) {// return "B and A";// } System.out.println(a2.show(b));//B是A的子类 所以使用show(A obj)----输出"B and A"System.out.println(a2.show(c));//C和D都是B 的子类 所以代表c和d是兄弟关系 使用show(A obj) ---输出"B and A"System.out.println(a2.show(d));//D直接使用show(D obj) ----输出"A and D"//b可以使用自己的方法 还可以使用继承过来父亲的方法 // public String show(D obj) {// return "A and D";// }public String show(A obj) {// return "B and A";// } //public String show(Object obj){ return "B and B"; }System.out.println(b.show(b));//B是A的子类 使用show(A obj) 输出结果是A and DSystem.out.println(b.show(c));//C和D都是B 的子类 所以代表c和d是兄弟关系 使用show(A obj) ---输出"B and A"System.out.println(b.show(d));//D直接使用show(D obj) ----输出"A and D"}}
分析
a1调用 A 里面的show方法
① System.out.println(a1.show(b));
B是D的父类,父亲不能放到孩子里 -- (A obj) "A and A"
②System.out.println(a1.show(c));
C和D 是兄弟关系 不能放到D里,放不下 --(A obj) "A and A"
③System.out.println(a1.show(d))
D类型可以放到D里边 --(D obj) "A and D"
a2 可以使用A 里面的show方法,也可以使用子类重写的父类的方法
public String show(D obj) {
return "A and D";
}
public String show(A obj) {
return "B and A";
}
④ System.out.println(a2.show(b));
B是A的子类 所以使用show(A obj)----输出"B and A"
⑤System.out.println(a2.show(c));
C和D都是B 的子类 所以代表c和d是兄弟关系 使用show(A obj) ---输出"B and A"
⑥System.out.println(a2.show(d));
D直接使用show(D obj) ----输出"A and D"
b可以使用自己的方法 还可以使用继承过来父亲的方法
public String show(D obj) {
return "A and D";
}
public String show(A obj) {
return "B and A";
}
public String show(Object obj){ return "B and B"; }
⑦System.out.println(b.show(b));
B是A的子类 使用show(A obj) 输出结果是A and D
⑧System.out.println(b.show(c));
C和D都是B 的子类 所以代表c和d是兄弟关系 使用show(A obj) ---输出"B and A"
⑨System.out.println(b.show(d));
D直接使用show(D obj) ----输出"A and D"