Pls clarify the confusions on main method. * Is it neccessary that a class having the main method has to be executed, assuming the file name is the same as this class? I've a class file a.java and have two classes, class a and class b in it. If i put the main method in class b, it compiles correctly but doesn't run but putting the main method in class a compiles and works correctly. * What is the relevance of making the class public (the file name being same as this class), when things work fine without specifying any modifiers to this class? Thanks
Post by:Ernest Friedman-Hill
As to your first question, compiling and running are two separate steps in most environments; you compile with "javac", and run with "java". If you use the two commands
then you should be able to run the main inside class b. For your second question: in toy examples, with classes named "a" and "b", and without using Java packages: nothing! It really doesn't matter at all. But if you have 100 classes, or 1000, then you don't want them all in one directory -- you want to organize them into packages. And you'll find, then, that non-public classes are "hidden" inside their package: they can't be accessed by classes in other packages. So while the difference between public and non-public classes doesn't matter now, it will definitely matter down the road.
Post by:geeta rai
, Ranch Hand
Thanks for the reply. Actually my second question was more for main method. I was under the impression that the class in which main method is written should be specified as public, accessible from anywhere but it works without specifying any modifiers too. Thanks anyway.
Post by:Herb Schildt
, Ranch Hand
Classes in Java have two access levels: public and default. The default access results when you do not explicitly use the public specifier. A class with default access can be accessed only by other code within the same package. However, if you are using the default package (i.e., if you are not specifying a package explicitly for your code) then your class is accessible by any other class also within the default package. In this situation, public access and default access are nearly indistiguishable. This is why your example works either way. [ October 01, 2003: Message edited by: Herb Schildt ]
bacon. tiny ad:
Thread Boost - a very different sort of advertising