Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why have a public class?

 
Fintan Conway
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
The normal convention I have come across in teaching java is that - in order to run a class as an application it must be declared public and have a 'public static void main(String s[])'. However this class will compile and run as an application.

Have I been mislead all these years? Is this something new in Java 1.4?
Also a class will compile and run if the name is all in lowercase. I was lead to believe that it had to have an initial capital. Is this just a convention rather than an enforced rule?
Many thanks,
Fintan
 
Raja Sagar Panamgipalli
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friend,
An Application i.e..a normal java application can consist of a number of class which can consist of different logic.However there will be only one main class that makes use of these specific classes ie..(by instantiating them).It is this class that must be made public.
In an application such as a normal HelloWorld program there is no effect
whether u declare it public or not,since there is only one class and the JVM will have no trouble finding it out.
(see JVM specification)
Regarding the convention for declaring class.It compels me to say that it more of our conveinence to declare that way.
In object oriented lang we basically declare a first letter in a class name in Capital letter and a method in a mix of both.i.e..

class HelloWorld{
public static displayHello(){
System.out.println(" Hello ");
}
public static void main(String[] args){
displayHello();
}
}
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Fintan
You can have any number of non public classes. But only one public class. This rule is imposed by the compiler not the language.
So you can have any no. of classes with default accessibility and you can name the file anything you wish. But in case you have a public class then the name of the file should be the public class name.
As it is neccessary to name the file after the public class. You can not have more than one public class.
[ October 31, 2003: Message edited by: Anupam Sinha ]
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To go back to the original question, why have a public class?
A class can only be instantiated from outside its package if the class is public. A class can only be extended from outside its package if it is public.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic