• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

public class for calling main

 
Bernd Stransky
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question about public class:
Code example:
class A { public static void main(String a[]) {} }
This code in file A.java compiles and runs with:
java A
What is the rule for having a public class in a java file?
I know the difference to <default>, protected and private, but I always thought that you need to have a public class (in this case public class A) when calling main in a Java application.
Any help is appreciated,
Bernd
 
Ragu Sivaraman
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Bernd Stransky:
Question about public class:
Code example:
class A { public static void main(String a[]) {} }
This code in file A.java compiles and runs with:
java A
What is the rule for having a public class in a java file?
I know the difference to <default>, protected and private, but I always thought that you need to have a public class (in this case public class A) when calling main in a Java application.
Any help is appreciated,
Bernd

Well its like this..
You can have the file name to be any name refering to any class name in a source file. If you do that and the class name you had used to save it doesnt have a main method, it will compile though but it may not run and give a runtime exception
But..
If you have a class as public, you must save the file in the class name that's defined public
HIH
Ragu
 
Bernd Stransky
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ragu Sivaraman:
Well its like this..
You can have the file name to be any name refering to any class name in a source file. If you do that and the class name you had used to save it doesnt have a main method, it will compile though but it may not run and give a runtime exception
But..
If you have a class as public, you must save the file in the class name that's defined public
HIH
Ragu

Thanks you - I was under the impression that public is mandatory for the class with main() method - OK, it works without as well.
-Bernd
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic