-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTest.java
More file actions
113 lines (96 loc) · 3.02 KB
/
Test.java
File metadata and controls
113 lines (96 loc) · 3.02 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package interfaces.part1;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
intro();
solution1();
solution2();
idealSolution();
}
private static void idealSolution(){
System.out.println("--------------- idealSolution --------------");
Walkable[] arr = new Walkable[4];
arr[0] = new Person2("Abu");
arr[1] = new Person2("Saeed");
arr[2] = new Person2("John");
arr[3] = new Duck2("duck1");
letAllWalkTogether(arr);
}
private static void letAllWalkTogether(Walkable[] arr){
for(Walkable obj : arr){
obj.walk();
}
}
private static void letDuckWalk(Duck[] list){
for(Duck duck : list) {
if(duck == null) continue;
duck.walk();
}
}
private static void letPersonWalk(Person[] list){
for(Person person : list) {
if(person == null) continue;
person.walk();
}
}
private static void solution2(){
Person[] persons = new Person[3];
persons[0] = new Person("Jack");
persons[1] = new Person("Jeff");
persons[2] = new Person("John");
letPersonWalk(persons);
Duck[] ducks = new Duck[3];
ducks[0] = new Duck("Ab");
ducks[1] = new Duck("Bc");
ducks[2] = new Duck("Ka");
letDuckWalk(ducks);
}
private static Method getWalkMethod(Object obj) {
Class c = obj.getClass();
Method walkMethod = null;
try {
walkMethod = c.getMethod("walk");
return walkMethod;
}
catch (NoSuchMethodException e) {
// walk() method does not exist
}
return null;
}
private static void letThemWalkUpdated(Object[] list){
for(Object obj : list) {
Method walkMethod = getWalkMethod(obj); // getting method reference
if (walkMethod != null) {
try {
walkMethod.invoke(obj); // calling walk method on the obj
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
private static void solution1(){
System.out.println("---------------- solution1 -------------------");
Object[] objects = new Object[4];
objects[0] = new Person("Jack");
objects[1] = new Person("Jeff");
objects[2] = new Person("John");
objects[3] = new Duck("Duck1");
letThemWalkUpdated(objects);
}
private static void letThemWalk(Person[] list){
for(Person person : list) {
if(person == null) continue;
person.walk();
}
}
private static void intro(){
Person[] persons = new Person[4];
persons[0] = new Person("Jack");
persons[1] = new Person("Jeff");
persons[2] = new Person("John");
//persons[3] = new Duck("Duck1"); // compile time error
letThemWalk(persons);
}
}