Does the order matter when declaring classes in Java?

Why this code does not even compile?

public class T {
    public static void main(String[] args) {
        class A extends B {}
        class B {}
        B a = new A();
    }
}

Error:

Error:(10, 25) java: cannot find symbol
  symbol:   class B
  location: class com.test.T
Error:(12, 15) java: incompatible types
  required: B
  found:    A

Does the order really matter when declaring such classes?

Jon Skeet
people
quotationmark

Yes, it matters for local classes. It's worth noting that local classes are incredibly rare in real code. I can only remember ever using one once. However, for the sake of interest...

From the JLS, section 6.3:

The scope of a local class declaration immediately enclosed by a block (ยง14.2) is the rest of the immediately enclosing block, including its own class declaration.

Now "rest" isn't terribly clear, but I believe it means "from this point onwards". So basically B isn't in scope in the declaration of A, hence the error.

For added fun, before the declaration of B you can refer to a different type called B:

public class T {

    public static void main(String[] args) {
        class A extends B {}
        class B {}
        B a = new A();
    }
}

class B {}

Gives:

error: incompatible types: A cannot be converted to B

people

See more on this question at Stackoverflow