What allows closures in the JLS?

S

Stefan Ram

What allows closures in the JLS? By "closures" I mean cases
like the following, where the parameter »i« is enclosed in
objects c0 and c1:

Main.java

public final class Main
{

public static java.lang.Runnable f( final int i )
{ return new java.lang.Runnable()
{ public void run()
{ java.lang.System.out.println( i ); }}; }

public static void main( final java.lang.String[] args )
{ final java.lang.Runnable c0 = f( 0 );
final java.lang.Runnable c1 = f( 1 );
c0.run();
c1.run(); }}

java.lang.System.out

0
1


The JLS, in fact contains the following word sequence:

"local variables from the surrounding method may be
referred to"

- JLS7, 8.1.3, Example 8.1.3-2.

and this is just what I was looking for. Why do I still post
this question here? Because this sentence "only" appears in
an example (Example 8.1.3-2). I am looking for the same
contents in a more normative part.

It would be nice if the JLS7 would contain some normative
part that allows this and also gives semantics for it (to
the extend that such local variables will keep their value
even when the lifetime of their method incarnation already
has ended). Also, it should be said somewhere that
parameters are also local variables in this sense. Possibly,
the JLS7 contains such wording and I just cannot find it.
 
S

Steven Simpson

The JLS, in fact contains the following word sequence:

"local variables from the surrounding method may be
referred to"

- JLS7, 8.1.3, Example 8.1.3-2.

and this is just what I was looking for. Why do I still post
this question here? Because this sentence "only" appears in
an example (Example 8.1.3-2). I am looking for the same
contents in a more normative part.


I think these might cover it:

The /scope/ of a declaration is the region of the program within which
the entity declared by the declaration can be referred to using a
simple name, provided it is visible (§6.4.1).
The scope of a formal parameter of a method (§8.4.1) or constructor
(§8.8.1) is the entire body of the method or constructor.


If an expression name consists of a single /Identifier/, then there
must be exactly one declaration denoting either a local variable,
parameter, or field visible (§6.4.1) at the point at which the
/Identifier/ occurs. Otherwise, a compile-time error occurs.


Also, this would be redundant if you couldn't reference parameters in an
inner class:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top