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{} public class Test3{
public static void main(String[] args){
A a = new B();
C c = new C();
System.out.println(a.show(c)); //为什么会输出B and A
}
}
我这输出的是 B and B
public String show(Object D){
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{}
public class T{
public static void main(String[] args){
A a = new B(); //new 出来的类a是属于B类型的
C c = new C();
System.out.println(a.show(c)); //这里调用的是B类的show方法,至于是第一个还是第二个要看参数的,c继承B,B继承A,从而调用的是第二个方法。
}
}
那个参数是D,后面少了一个类:class D extends B{}
而 B类中show(A obj) 中的参数真正c的父类 所以会输出B and 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){ //对父类的show方法进行了重写 return ("B and A");
}
}
class C extends B{} public class Test3{
public static void main(String[] args){
A a = new B(); //父类对象引用子类对象
C c = new C();
System.out.println(a.show(c)); //输出的是子类的show方法,因为子类对父类的show方法进行了重写,如果没重写,就输出父类的show方法内容
}
}
public String show(A obj){
return ("B and A");
}
对A类里面的这个方法进行了覆盖,这个时候父类A中就变成这个样子:
class A {
public String show(Object D){
return ("A and D");
}
public String show(A obj){
return ("B and A");
}
}
所以当a.show(c)的时候他会调用A类里面第二个方法 return ("B and A");
public String show(A obj){
return ("B and A");
}
改成:
public String show1(A obj){
return ("B and A");
}
在运行下就看的出区别了
什么跟什么???差点把我都弄糊涂了!!
LZ你的疑问是:“为什么c继承B,B继承A,就要调用第二个方法?”吧??
class A {
public String show(Object D){
return ("A and D");
}
public String show(A obj){
return ("A and A");
}
}
class B extends A{
public String show(B obj){ //这个方法别搞错了,这个不是重写!!参数(类型,个数,次序)必须相同才是重写。A类中没有这个方法,
//这个是B类自己新定义的方法!!
return ("B and B");
}
public String show(A obj){ //这个才是重写!!!
return ("B and A");
}
}
class C extends B{} public class Test3{
public static void main(String[] args){
A a = new B(); //先不说那么多多态的概念,你就理解为 a只能调用A和B类共有的方法和属性。那么他们共有只有public String show(A obj){
C c = new C();
System.out.println(a.show(c)); //所以a.show()调用的只有public String show(A obj)这个方法!不存在传参时的重载问题!!
}
}