When is "public" needed in a class definition?
<p>This question relates to where <strong>classes</strong> themselves (not their methods or data) need to be declared as public.</p>

<p>Currently I'm a Java noob, self taught with just the very basics. I'm familiar with several other languages, but in Java I've only written extremely basic programs, like with everything in the one main class (one file).</p>

<p>So today I decided to try something new, and put classes in separate files. What surprised me was that when I placed a class in a separate file, that this class was accessible to the main program, even if it wasn't marked "public".</p>

<p>For the sake of a definite example, lets say I've got <strong>just</strong> two files in the one folder. File "mainprog.java" containing the following:</p>

<pre><code>class mainprog {
    public static void main(String[] args) {
        hello myHello = new hello();
        myHello.sayHello();
    }
}
</code></pre>

<p>And file "hello.java" containing the following:</p>

<pre><code>class hello {
    void sayHello() {
    System.out.println("Hello world");
    }
}
</code></pre>

<p>Nothing in "hello" is specified as public, but this compiles and runs just fine with</p>

<pre><code>javac mainprog.java
java mainprog
</code></pre>

<p>So I'm just kind of wondering where "public" really is needed for class definitions?</p>

<p><strong>EDIT to add new information</strong>
As suggested by answers below, I tried adding a "package" statement to each file, so as to make them from different packages. As expected the access to class "hello" was then denied unless I made both the class "hello" and it's method "sayHello() public. Thanks everyone.</p>
