1
+ package advancedClassDesign ;
2
+
3
+ /**
4
+ *
5
+ * @author chengfeili
6
+ * Jun 27, 2017 6:11:11 PM
7
+ *
8
+ * Polymorphism is the ability for an object to vary its behavior based
9
+ * on its type
10
+ *
11
+ * Even though HumanBeing is used, the JVM decides at runtime which
12
+ * method to call based on the type of the object assigned, not the
13
+ * variable's reference type.
14
+ *
15
+ * This is called virtual method invocation, a fancy name for
16
+ * overriding.
17
+ *
18
+ * Overriding is also known as dynamic polymorphism because the type of
19
+ * the object is decided at RUN time.
20
+ *
21
+ * In contrast, overloading is also called static polymorphism because
22
+ * it's resolved at COMPILE time.
23
+ */
24
+ public class Polymorphism {
25
+ public static void main (String [] args ) {
26
+ HumanBeing [] someHumans = new HumanBeing [3 ];
27
+ someHumans [0 ] = new Man ();
28
+ someHumans [1 ] = new Woman ();
29
+ someHumans [2 ] = new Baby ();
30
+ for (int i = 0 ; i < someHumans .length ; i ++) {
31
+ someHumans [i ].dress ();
32
+ System .out .println ();
33
+ }
34
+ }
35
+ }
36
+
37
+ abstract class HumanBeing {
38
+ public abstract void dress ();
39
+ }
40
+
41
+ class Man extends HumanBeing {
42
+ public void dress () {
43
+ System .out .println ("Man" );
44
+ }
45
+ }
46
+
47
+ class Woman extends HumanBeing {
48
+ public void dress () {
49
+ System .out .println ("Woman" );
50
+ }
51
+ }
52
+
53
+ class Baby extends HumanBeing {
54
+ public void dress () {
55
+ System .out .println ("Baby" );
56
+ }
57
+ }
0 commit comments