Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Language Specification - Cannot understand 'BlockStatement'

I've been examining the Java Language Specification here (instead I should be out having a beer) and I am curious about what a method can contain. The specification states a method body can contain a block

MethodBody:
    Block

Where a 'Block' contains 'BlockStatements'. The 'BlockStatement' rule looks like this:

BlockStatement : 
    LocalVariableDeclarationStatement
    ClassOrInterfaceDeclaration
    [Identifier :] Statement

I can understand the 'LocalVariableDeclarationStatement' which could be

[final] int x, y, z;

However, I don't get why the 'ClassOrInterfaceDeclaration' rule is there. This rule looks like:

ClassOrInterfaceDeclaration: 
    ModifiersOpt (ClassDeclaration | InterfaceDeclaration)

ClassDeclaration: 
    class Identifier [extends Type] [implements TypeList] ClassBody

InterfaceDeclaration: 
    interface Identifier [extends TypeList] InterfaceBody

What's going on here - You can't declare a class or interface within a block surely? Can someone help elucidate this confusion please?

Update: I can define a class within a method, but the following won't work:

public class Foo {
    public void doFoo() {
        interface dooJa {
            int bar();
        }
    }
}

The compiler complains stating "The member interface dooJa can only be defined inside a top-level class or interface"... any explanations?

like image 904
Joeblackdev Avatar asked Jul 09 '11 20:07

Joeblackdev


2 Answers

Oh yes you can declare a class inside a method body. :-)

class A {

    public void doIt() {
        class B {}
        B b = new B();
        System.out.println(b.getClass());
    }

}
like image 145
Sanjay T. Sharma Avatar answered Sep 20 '22 03:09

Sanjay T. Sharma


You've made a good observation about interfaces not working anymore. The reason is you that are looking at a very old version of the grammar. It looks to be over 10 year old. Take a look the grammar for Java 6 (what you are probably testing with):

http://www.it.bton.ac.uk/staff/rnb/bosware/javaSyntax/rulesLinked.html#BlockStatement

You will see blockstatement:

BlockStatement: LocalVariableDeclarationStatement ClassDeclaration Statement

like image 35
Dave L. Avatar answered Sep 22 '22 03:09

Dave L.