您的位置:首页 > 编程语言 > Java开发

Java中多态的实例

2015-06-03 12:43 411 查看
public class cf {

/**
* 实际上这里涉及方法调用的优先问题,
* 优先级由高到低依次为:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。
*/
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)); // ① A and A
System.out.println(a1.show(c)); // ② A and A
System.out.println(a1.show(d)); // ③ A and D
System.out.println(a2.show(b)); // ④ B and A
System.out.println(a2.show(c)); // ⑤ B and A
System.out.println(a2.show(d)); // ⑥ A and D
System.out.println(b.show(b)); // ⑦ B and B
System.out.println(b.show(c)); // ⑧ B and B
System.out.println(b.show(d)); // A and 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 {
}


复制去Google翻译翻译结果

搜索

复制
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: