Reputation: 32807
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.
Upvotes: 0
Views: 1051
Reputation: 12174
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
.
Upvotes: 5