Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Public class or just simply class?

586635Jun 3 2010 — edited Jun 4 2010
As I continue my reading into various books there are some books which will have you add the access modifier public in front of your classname. Other books will just have you leave it out. I tried out a simple program that declared a class in a separate file and then the second file was the main class file with the main method.

It didn't matter whether or not I removed the keyword public in front of the name of my class in the first file. The program compiled and ran just fine. So I'm doing some looking on the web trying to understand what the word public means when it's placed in front of your classname.

According to Sun:

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 (packages are named groups of related classes?you will learn about them in a later lesson.)

I picked this up from some other source:

Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package.

So if I understand this correctly if I place the word public in front of my classname my class is visible to all classes and all packages?

And if I don't place the word public in front of my classname then the class that I defined is only accessible only by other classes in the same package whatever that package happens to be?

So if I wrote this:
public class MyVehicle
{
//////////
}
Then if I imported a package called import.java.GiveMeSomePaintingTools;

Then the classes contained in the GiveMeSomePaintingTools would have access to the MyVehicle class that I made?

And if I just wrote this:
class MyVehicle
{
////////
}
Then the classes in the package GiveMeSomePaintingTools would not have access to the class I made?

That's what I gather...

Edited by: 357mag on Jun 3, 2010 5:53 AM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 2 2010
Added on Jun 3 2010
5 comments
341 views