In the Java DOM/AST (http://help.eclipse.org/indigo/topic/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/dom/package-tree.html) why does an Initializer contain a Block and why is a MethodInvocation an Expression and not a Statement?
I mean, given the code
int a = Integer.parseInt("1");
the ASTView plugin shows me only INITIALIZER > MethodInvocation
Can there ever be an Initializer that really has a Block element?
Moreover, if I have a method like this
public void thisMethod(){
System.out.println();
}
MethodInvocation is wrapped into an ExpressionStatement. But why isn't MethodInvocation a Statement? Just a simple System.out.println() is a valid "Statement". An Expression in the sense of the Java DOM/AST lacks the ability to stand for itself.
Maybe I just didn't the get the whole idea of the separation between Expression and Statement.
The AST tree is designed to reflect the syntax rules of the programming language.
Syntactically, an Initializer consists of a block with an optional static
modifier before it. So it’s the most natural implementation having an Initializer
class consisting of a Block
and modifiers (inherited from BodyDeclaration
). So I don’t understand why you question it.
Example of initializers:
class Foo {
static {
System.out.println("static initializer");
System.out.println("class Foo now initialized");
}
{
System.out.println("instance initializer");
System.out.println("an instance of Foo has been created");
}
}
Expressions and statements are two different syntactic constructs. There are places where only either an expression or a statement is allowed. But there are constructs like method invocations which are Expression Statements which means the can fulfill both roles, Expression and Statement. They can be invoked stand-alone for their side-effects but also at places where a value is required.
But since Java does not allow multiple inheritance you cannot create an AST class ExpressionStatement
inheriting from both Expression
and Statement
. So you need a solution like in the Eclipse AST where ExpressionStatement
inherits from one and wraps the other. The decision which one to inherit and which one to wrap is easy: you can create a Statement
implementation (subclass) which drops the result of the Expression
it has wrapped but you cannot create an Expression
implementation which provides a result for a Statement
that provides no result through its interface. An alternative to such an implementation would be the use of interfaces.