aspose file tools*
The moose likes Beginning Java and the fly likes Main method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Main method" Watch "Main method" New topic
Author

Main method

geeta rai
Ranch Hand

Joined: Sep 18, 2003
Posts: 48
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
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
geeta rai
Ranch Hand

Joined: Sep 18, 2003
Posts: 48
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.
Herb Schildt
Author
Ranch Hand

Joined: Oct 01, 2003
Posts: 239
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 ]

For my latest books on Java, including my Java Programming Cookbook, see HerbSchildt.com
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Main method