FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
OnJava8-Examples/innerclasses/LocalInnerClass.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
/
LocalInnerClass.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
65 lines (63 loc) · 1.64 KB
Breadcrumbs
OnJava8-Examples
/
innerclasses
/
LocalInnerClass.java
Copy path
File metadata and controls
65 lines (63 loc) · 1.64 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
// innerclasses/LocalInnerClass.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.
// Holds a sequence of Objects
interface
Counter
{
int
next
();
}
public
class
LocalInnerClass
{
private
int
count
=
0
;
Counter
getCounter
(
final
String
name
) {
// A local inner class:
class
LocalCounter
implements
Counter
{
LocalCounter
() {
// Local inner class can have a constructor
System
.
out
.
println
(
"LocalCounter()"
);
}
@
Override
public
int
next
() {
System
.
out
.
print
(
name
);
// Access local final
return
count
++;
}
}
return
new
LocalCounter
();
}
// Repeat, but with an anonymous inner class:
Counter
getCounter2
(
final
String
name
) {
return
new
Counter
() {
// Anonymous inner class cannot have a named
// constructor, only an instance initializer:
{
System
.
out
.
println
(
"Counter()"
);
}
@
Override
public
int
next
() {
System
.
out
.
print
(
name
);
// Access local final
return
count
++;
}
};
}
public
static
void
main
(
String
[]
args
) {
LocalInnerClass
lic
=
new
LocalInnerClass
();
Counter
c1
=
lic
.
getCounter
(
"Local inner "
),
c2
=
lic
.
getCounter2
(
"Anonymous inner "
);
for
(
int
i
=
0
;
i
<
5
;
i
++)
System
.
out
.
println
(
c1
.
next
());
for
(
int
i
=
0
;
i
<
5
;
i
++)
System
.
out
.
println
(
c2
.
next
());
}
}
/* Output:
LocalCounter()
Counter()
Local inner 0
Local inner 1
Local inner 2
Local inner 3
Local inner 4
Anonymous inner 5
Anonymous inner 6
Anonymous inner 7
Anonymous inner 8
Anonymous inner 9
*/
Back
|
FazBrowse Home
|
New Git URL