I'm starting to learn java and have created my first hello world function in Eclipse. I've noticed that the following two functions, both in the default package of the src folder in my java project, seem to do the same thing:
class HelloWorld {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
and
public class HelloWorld {
public static void main(String[] args){
System.out.println("Hello World!");
}
}
Both successfully print 'Hello World!' to the console.
I've read a bit about different class types, but am unsure what type of class I would be declaring with the first function. What's the difference between these two functions? Does java make my hello world class in the first case public?
Class
that is not declaring itself as public
is package protected
, meaning that the class
it is only accessible in that package.
Very useful summary of acccess modifiers on stackoverflow. More at oracle
Example:
So let's say you have the following package structure:
com
stackoverflow
pkg1
public Class1
Class2
pkg2
OtherClass
Class2
can only be used by Class1
, but not by OtherClass
It's all about class visibility!
A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With