wood burning stoves*
The moose likes Beginning Java and the fly likes one public class per file is a must ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "one public class per file is a must ??" Watch "one public class per file is a must ??" New topic
Author

one public class per file is a must ??

Karolin Franks
Greenhorn

Joined: Aug 24, 2005
Posts: 4
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?

Thanks
Karolin.
Thomas Paul Bigbee
Ranch Hand

Joined: Jun 28, 2005
Posts: 71
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.

Tom
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
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 ]
Ramesh Shanmugam
Ranch Hand

Joined: Sep 13, 2004
Posts: 132
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.

Thanks and Regards
Ramesh


Ramesh Shanmugam - SCJP 1.5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: one public class per file is a must ??
 
Similar Threads
Rules regarding Public Classes
query
question about what makes a class public
2 public classes in one file??
What will be the name of .java file?