• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Public Classes

 
Aneesh Kannel
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 "Foo.java". 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.
 
Jaideep Kshirsagar
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 'Jaideep.java' 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
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... 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
Posts: 45
Eclipse IDE Tomcat Server Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic