Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are undeclared classes in Java public?

Tags:

java

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?

like image 407
ckersch Avatar asked Apr 24 '13 15:04

ckersch


2 Answers

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

like image 87
Matyas Avatar answered Nov 15 '22 08:11

Matyas


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

like image 31
TheEwook Avatar answered Nov 15 '22 09:11

TheEwook