Reputation: 7687
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?
Upvotes: 5
Views: 2826
Reputation: 13702
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
Upvotes: 10
Reputation: 3408
This took me about 2 seconds to find on Google:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
In answer to your question, the default modifier is package protected
, meaning it can only be accessed within the package, but next time please do some research before posting a question, as it took you more time to write the question that it would have to search
Upvotes: 1
Reputation: 121998
It is protected class ,you cannot access that class out side the package
.
If you not specify anything its by default protected
Upvotes: 0
Reputation: 11117
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
Upvotes: 1