Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the order matter when declaring classes in Java?

Tags:

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?

like image 689
Finkelson Avatar asked Jan 07 '23 16:01

Finkelson


1 Answers

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

like image 147
Jon Skeet Avatar answered Feb 02 '23 10:02

Jon Skeet