多态是面向对象的核心思想之一,多态的实现有三要素: 1、 存在继承 2、子类对父类的方法进行了重写 3、父类引用指向子类对象。

  前面说的还是有点虚,下面通过一个例子来深入理解多态。

  程序代码如下,给出对应的输出:

 1 public class Polymorphism {
 2     public static void main(String[] args) {
 3         A a1 = new A();
 4         A a2 = new B();
 5         B b = new B();
 6         C c = new C();
 7         D d = new D();
 8 
 9         a1.show(b);
10         a1.show(c);
11         a1.show(d);
12         a2.show(b);
13         a2.show(c);
14         a2.show(d);
15         b.show(b);
16         b.show(c);
17         b.show(d);
18         b.show(a1);
19         a1.show(a1);
20         a2.show(a1);
21     }
22 }
23 
24 class A {
25     public void show(A a) {
26         System.out.println("A and A");
27     }
28 
29     public void show(D d) {
30         System.out.println("A and D");
31     }
32 }
33 
34 class B extends A {
35     public void show(B b) {
36         System.out.println("B and B");
37     }
38 
39     public void show(A a) {
40         System.out.println("B and A");
41     }
42 }
43 
44 class C extends B {
45 }
46 
47 class D extends B {
48 }
Polymorphism

相关文章:

  • 2021-07-24
  • 2022-03-07
  • 2022-01-17
  • 2021-10-01
  • 2022-12-23
  • 2022-12-23
  • 2021-11-11
  • 2021-06-25
猜你喜欢
  • 2021-11-17
  • 2022-12-23
  • 2021-09-16
  • 2021-06-28
  • 2021-06-14
  • 2022-12-23
  • 2021-11-10
相关资源
相似解决方案