• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

One Public Class Per Source File?

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All!

I had this doubt that, why should a source file have only one public class?


1. If a source file has more than one public class, the compiler won't allow. why?
 
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thats because the file name of the source code needs to be the same as the public class it contains. Would be difficult to know what to call the file if you could put two public classes inside one source file.
[ October 10, 2004: Message edited by: Dominic Steng�rd ]
 
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
javac compiler and the java interpreter need a way to search your entire CLASSPATH for the classes you require in your program. The only externally visible identifier of a compiled .class file is the filename. So the filename must be enough to find the classes you need. If there were a public class named Abc in a .class file named Fgh.class, javac and java would have no way to find it.

You might ask about classes with protected or package access. There, the directory names found in the directories in your CLASSPATH provide a visible trail to your classes.
 
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


You might ask about classes with protected or package access



A top-level class can never have protected access.

Here is an example of some source with two public classes in one source file:



To better rephrase, "You can't have more than one public top-level class in a single Java source file."
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic