简体   繁体   中英

Places where an expression can occur as per the JLS?

Consider the Article §15.1 regarding places where the expression can occur:

An expression occurs in either:

• The declaration of some (class or interface) type that is being declared: in a field initializer, in a static initializer, in an instance initializer, in a constructor declaration, in a method declaration, or in an annotation.

• An annotation on a package declaration or on a top level type declaration.

I don't think this is exhaustive list of all occurrence places for expression - as eg:

int a=23; //declaration of a local type
a=33; //this is re-initialization of the type

//or like a simple method invocation from inside a method like
foo();
  • The places where we are trying to re-initialize the expression are not highlighted by this clause.
  • also the simple method invocation is not being highlighted in the above clause - even though it is a formal expression.

Is the clause above correct - or is just a casual statement in the JLS?

That clause is actually true, though it is not stated in a precise way.

For example:

  • a=33;

    The a=33 is an expression, and when followed by a ; it is also an expression statement. An expression statement is only allowed where other statements are allowed; ie within a method or constructor declaration (in the body ), or in an instance or static initializer (block).

    Note that in the JLS, a method's body is part of the method's declaration. That is why we can say that statements are within a method declaration.

  • foo();

    The foo() call is an expression, and when followed by a ; it is also an expression statement; see above.

It is a matter of understanding what is meant by "in" in this context. It means "inside of" rather than "directly inside of".

The imprecision arises when you consider that an expression statement that is inside of a method declaration that is inside of a class is... also indirectly inside the class.

You could argue that the clause descriptive rather than normative since they don't specify precisely what "in" means in this context. But even so, the description is correct if you interpret it as above.


Your int a=23; "example" is not an expression, so it is not apropos to the point you are trying to make. It could be a statement, or it could be a (package private) field declaration that is "in" a class or interface declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM