FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
OnJava8-Examples/innerclasses/Callbacks.java at master · xinan-w/OnJava8-Examples · GitHub
xinan-w
/
OnJava8-Examples
Public
forked from
BruceEckel/OnJava8-Examples
Notifications
You must be signed in to change notification settings
Fork
0
Star
1
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
OnJava8-Examples
/
innerclasses
/
Callbacks.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
81 lines (75 loc) · 1.76 KB
Breadcrumbs
OnJava8-Examples
/
innerclasses
/
Callbacks.java
Copy path
File metadata and controls
81 lines (75 loc) · 1.76 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
// innerclasses/Callbacks.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Using inner classes for callbacks
// {java innerclasses.Callbacks}
package
innerclasses
;
interface
Incrementable
{
void
increment
();
}
// Very simple to just implement the interface:
class
Callee1
implements
Incrementable
{
private
int
i
=
0
;
@
Override
public
void
increment
() {
i
++;
System
.
out
.
println
(
i
);
}
}
class
MyIncrement
{
public
void
increment
() {
System
.
out
.
println
(
"Other operation"
);
}
static
void
f
(
MyIncrement
mi
) {
mi
.
increment
(); }
}
// If your class must implement increment() in
// some other way, you must use an inner class:
class
Callee2
extends
MyIncrement
{
private
int
i
=
0
;
@
Override
public
void
increment
() {
super
.
increment
();
i
++;
System
.
out
.
println
(
i
);
}
private
class
Closure
implements
Incrementable
{
@
Override
public
void
increment
() {
// Specify outer-class method, otherwise
// you'll get an infinite recursion:
Callee2
.
this
.
increment
();
}
}
Incrementable
getCallbackReference
() {
return
new
Closure
();
}
}
class
Caller
{
private
Incrementable
callbackReference
;
Caller
(
Incrementable
cbh
) {
callbackReference
=
cbh
;
}
void
go
() {
callbackReference
.
increment
(); }
}
public
class
Callbacks
{
public
static
void
main
(
String
[]
args
) {
Callee1
c1
=
new
Callee1
();
Callee2
c2
=
new
Callee2
();
MyIncrement
.
f
(
c2
);
Caller
caller1
=
new
Caller
(
c1
);
Caller
caller2
=
new
Caller
(
c2
.
getCallbackReference
());
caller1
.
go
();
caller1
.
go
();
caller2
.
go
();
caller2
.
go
();
}
}
/* Output:
Other operation
1
1
2
Other operation
2
Other operation
3
*/
Back
|
FazBrowse Home
|
New Git URL