File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Public Classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Public Classes" Watch "Public Classes" New topic

Public Classes

Aneesh Kannel

Joined: Oct 23, 2007
Posts: 8
"Files with no public classes can have a name that
does not match any of the classes in the file."

Well I have read this from the Java SCJP Study Guide

Please explain to me this with Example.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
In Java, a top-level (not nested or inner) class that is declared public must have a source file whose name is the name of the class, plus ".java". So source for public class Foo must be written in file "". It follows from this that there can be a maximum of one top-level public class per source file.

For non-public top-level classes, there is no such restriction. Source for a non-public top-level class can be in a file of any name, plus ".java". There can be any number of non-public top-level classes in a single source file.

However, it is bad practice to make use of this laxity. Non-public top-level classes should be kept to a single class per file, and that file should be named as the class, plus ".java", just like it was a public class.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Jaideep Kshirsagar

Joined: Aug 29, 2007
Posts: 27
Consider this code with no public class

We can specify any name for the file containing this code (as long as we dont have public class in there). Suppose we create a file called '' containing this code & compiled it. At compilation two different class files 'JK.class' & 'YO.class' will be generated. I guess now the point will be clearer to you.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
... but one shouldn't ever do this.

The example is purely to show something that is legal, not to say it is acceptable practice.
Puneet Mittal
Ranch Hand

Joined: Dec 18, 2007
Posts: 45

hi jaideep how are you.
i agree to your above code explaination but what if i run this file. i mean by what nahme shud i run this file. if i run this file as "java.Jk" at first time and "java.Yo" so then will it run successfully in both the cases.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: Public Classes
It's not a secret anymore!