Hi, I just wanted to make something clear. I have read many places that 'there can be only one public class per file.' Also I have read that 'the name of the public class should match the name of the file.' But I'm wondering about the following situations: (1) What if there is no public class in a file? And what if there are 2 classes with default access modifiers? (2) If I have a superclass A and a subclass B. A is public and B is default access modifier. When I do "javac B.java", it's not compiling a public class. Is it correct way of doing?
You don't have to have a public class in a file, you don't even have to have a class in a file (interfaces). The decision to make a class public or default has to do with the visibility of that class from outside the package in which it is located. You could have a file full of default classes, compile the file and all classes within said file would compile.
When you compile a file, you should always use the name of that file.
A java source can have zero or more public class declarations. Most java compilers will accept zero or one public class declarations. It makes the compiler's job a lot easier (and more efficient) when it comes to managing dependencies out of the current package.
Not to confuse matters but there is no rule against having more than one public class in a file. There is no rule that says you need files, either. Java works from "compilation units", a term borrowed from C++ and C. With rare exceptions that's a file structure as defined by the host operating system. [ August 24, 2005: Message edited by: Rick O'Shay ]
It is not a must that a Java File name and Class name shoud be the same. That is you can have a Different Filename and can have Different Classname but you should be careful while running the Program. While you run the program you need to use only the class Name. But while compiling you can use the Filename to Compile.