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