-
Notifications
You must be signed in to change notification settings - Fork 1
/
interfaceDemo3.java
123 lines (96 loc) · 2.79 KB
/
interfaceDemo3.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
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
114
115
116
117
118
119
120
121
122
123
package Basics;
// https://www.youtube.com/watch?v=rM2f0mTie_Q&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=352
// https://www.youtube.com/watch?v=JQzwqQfzl08&list=PLmOn9nNkQxJH0qBIrtV6otI0Ep4o2q67A&index=353
// define a rule, standard, format
interface USB {
// attr
// method
void start();
void stop();
}
/**
* Interface part 3
*
* <p>1) interface using : reflects OOP's Polymorphism 2) interface essentially defines the
* "format", "standard" -> that can be implemented by the class
*
* <p>3) using cases : -> JDBC for DB
*
* <p>4) during development, we usually do "interface facing" development
*/
public class interfaceDemo3 {
public static void main(String[] args) {
// run
Computer pc1 = new Computer();
// wrong : 'USB' is abstract; cannot be instantiated
// pc1.transferData(new USB());
/** DEMO 1: interface's non anonymous class and non anonymous instance */
// will use the Flash class, which implements USB interface
Flash flash = new Flash();
pc1.transferData(flash);
System.out.println("============");
/** DEMO 2: interface's non anonymous class and anonymous instance */
pc1.transferData(new Printer());
System.out.println("============");
/** DEMO 3: interface's anonymous class and non anonymous instance */
USB phone =
new USB() {
@Override
public void start() {
System.out.println("phone start");
}
@Override
public void stop() {
System.out.println("phone stop");
}
};
pc1.transferData(phone);
System.out.println("============");
/** DEMO 4: interface's anonymous class and anonymous instance */
pc1.transferData(
new USB() {
@Override
public void start() {
System.out.println("ipod start");
}
@Override
public void stop() {
System.out.println("ipod stop");
}
});
}
}
class Computer {
// attr
// method
// NOTE : this method gets any implementation which from USB interface
// and use its start, stop method, while start, stop method
// are NOT implemented in USB (USB is an interface), but
// in the implementation of USB (e.g. Flash, Printer)
public void transferData(USB usb) {
usb.start();
// code that implements data transfer
usb.stop();
// code that implements stop
}
}
class Flash implements USB {
@Override
public void start() {
System.out.println("Flash start");
}
@Override
public void stop() {
System.out.println("Flash stop");
}
}
class Printer implements USB {
@Override
public void start() {
System.out.println("Printer start");
}
@Override
public void stop() {
System.out.println("Printer stop");
}
}