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.

Community
  • 1
  • 1
zurfyx
  • 31,043
  • 20
  • 111
  • 145
  • 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`. – Anya Shenanigans Jan 27 '14 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) – Mark W Jan 27 '14 at 22:19
  • This is what javac does. There are two classes, hence two class files. – Hot Licks Jan 27 '14 at 22:23

1 Answers1

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.

ps-aux
  • 11,627
  • 25
  • 81
  • 128