0

Let's say I have a A.java with two classes (a public one and a private) both in the same file.

public class A{
    public static void main(string[] args){
        ...
    }
}

class B{
    ...
}

Why is Java automatically automatically creating a A.class and a B.class when compiling the A.java?

Is it to avoid this sort of problems? https://stackoverflow.com/a/2336762/2034015

What happens if Foo.java refers to Baz but not Bar and we try to compile Foo.java? The compilation fails with an error like this:

Foo.java:2: cannot find symbol symbol : class Baz location: class Foo private Baz baz; ^ 1 error

Also, I know that the right way to work with Java is a file per class, but I wonder why Java does this.

3
  • 2
    java does this because it's a class-file per class, regardless of their public/private attributes. inner classes get called outer$inner, and anonymous classes get called outer$number. Commented Jan 27, 2014 at 22:17
  • Agreed, one class per file. The inner classes get the $ syntax, and require an instance of the preceding class to be instantiated before one of the type following the $ can be. (Inner classes require a reference to the containing type) Commented Jan 27, 2014 at 22:19
  • This is what javac does. There are two classes, hence two class files. Commented Jan 27, 2014 at 22:23

1 Answer 1

5

Java works on the principle of .class files which are generated from your source code. You can have only one public class per file but many other classes (including inner/ anonymous / static etc. - inner classes have $ in name preceded by outer class, anonymous have just numbers after $) in one file and still it will be compiled to more classes. So the relation would be source file : byte-code file - 1 : n.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.