实例一:
class Animal {
public void speak( Animal p) {System.out.println("Animal Speak!");}
}
class Dog extends Animal {
public void speak(Animal p) {System.out.println("汪!");}
public void speak(Dog t) { System.out.println("汪汪");}
public static void main(String[] args) {
Animal p1 = new Animal () ;
Animal p2 = new Dog () ;
Dog p3 = new Dog () ;
p1.speak( p1 ) ;//Animal Speak!
p1.speak( p2 ) ;//Animal Speak!
p1.speak( p3 ) ;//Animal Speak!
p2.speak( p1 ) ;//汪!
p2.speak( p2 ) ;//汪!
p2.speak( p3 ) ;//汪!
p3.speak( p1 ) ;//汪!
p3.speak( p2 ) ;//汪!
p3.speak( p3 ) ;//汪汪!
}
}
运行结果如下:
Animal Speak!
Animal Speak!
Animal Speak!
汪!
汪!
汪!
汪!
汪!
汪汪
实例二:
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 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("-------------------------");
System.out.println(a2.show(b));
System.out.println(a2.show(c));
System.out.println(a2.show(d));
System.out.println("-------------------------");
System.out.println(b.show(b));
System.out.println(b.show(c));
System.out.println(b.show(d));
}
}
输出结果:
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