Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why public keyword is necessory here?

 
vianyrajnish rajnish
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,


This is a simple java program -----

public class HelloWorldApp
{
public static void main(String arg[])
{
System.out.println("Hello World!");
}
}

here why do i declare -- public class HelloWorldApp -- for the class .?
if i remove (public) this i do get error..why is this?


can anyone please answer?




-- vinay rajnish
 
Maurizio Nagni
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generaly it is not an error to set "default" the class, but the error appears if you try to run it throught the "java HelloWorldApp" command; in this case the JVM cannot access the main method (because the class is not public).

To test that it just try to modify your HelloWorldApp file as



Note that in this case the code will give you an error if you define public the Test class because as defined in the Java syntax one file can contain one public class with a public static void main(String[] args) method.

Ciao
 
asha ganapathy
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the keyword "public" is used so that other classes in the same package or in the different package can use this class.
If you dont declare HelloWorldApp class as public it means its using a default access(you can use this class only in the current package, hence even if you dont use public keyword for HelloWorldApp there should not be any compiler error.
 
vianyrajnish rajnish
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,

thanks for helping .... all of you are correct

thanks for helping with clearing the concepts..

vinay rajnish
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic