package lu.test;
/*
* a1.show(b):调用的是A中show(A)
* a1.show(c)调用的是A中show(A)
* a1.show(d)调用的是show(D) 正常调用本类方法。
* a2.show(b)调用A.show(A) 方法show(B)并未被重写故调用的是父类的方法。
* a2.show(c) 同上。
* a2.show(d)将子类对象赋给父类引用,调用的是自父类的方法。
* b.show(b) 调用自己的方法
* b.show(c) 调用自己的show(B)
* 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{}
public class TestRelativeClass {
public static void main(String arg[]){
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));
}
}
/*
* a1.show(b):调用的是A中show(A)
* a1.show(c)调用的是A中show(A)
* a1.show(d)调用的是show(D) 正常调用本类方法。
* a2.show(b)调用A.show(A) 方法show(B)并未被重写故调用的是父类的方法。
* a2.show(c) 同上。
* a2.show(d)将子类对象赋给父类引用,调用的是自父类的方法。
* b.show(b) 调用自己的方法
* b.show(c) 调用自己的show(B)
* 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{}
public class TestRelativeClass {
public static void main(String arg[]){
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));
}
}
本文通过具体的Java代码示例,详细解析了多态性的概念及其应用。包括不同类之间的方法调用过程,以及如何根据对象的实际类型来决定调用哪个方法。
7889

被折叠的 条评论
为什么被折叠?



