Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java compilation of a .java file without a public class

Tags:

java

Okay, so a java source file must have at least one public class and the file should be called "class-name.java". Fair enough.

Hence, if I have a class, then the following would compile:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}

But what bugs me is that if I remove the 'public' access modifier from the above code, the code still compiles. I just don't get it. Removing it, the code looks like:

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}

In the above code, since I removed the public access modifier, my class has default or package access, i.e. it can't be accessed from the outside world, only from within the package.

So my question is, how does the above code compile ? The file HelloWorld.java in this case does not have a public HelloWorld class (only a package-private HelloWorld.class) and thus to my understanding should not compile.

like image 898
anon1981 Avatar asked Oct 03 '11 10:10

anon1981


3 Answers

a java source file must have at least one public class and the file should be called class-name.java

Incorrect, a top level class does not have to be declared public. The JLS states;

If a top level class or interface type is not declared public, then it may be accessed only from within the package in which it is declared.

See http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#104285 section 6.6.1.

like image 163
Qwerky Avatar answered Oct 01 '22 18:10

Qwerky


You can place non-public class in a file, and it's not a bug but feature.

Your problem is on level of packaging, not compile. Because you can compile this file with non-public class, but you can't call it from outside, so it's not working as application base class

Like this:

// [+] single file: SomeWrapper.java 

public class SomeWrapper {
    ArrayList<_PrivateDataType> pdt;
}
// [-] single file: SomeWrapper.java 

// [+] single file: _PrivateDataType.java 
class _PrivateDataType {
    // members, functions, whatever goes here
}

// [-] single file: _PrivateDataType.java 
like image 22
Marek Sebera Avatar answered Oct 01 '22 17:10

Marek Sebera


A main method is just like any other method. The only difference is that it may be invoked from the command line with the java command. Even if the main method is not visible from the command line, the class can still be used like any other Java class, and your main method may be invoked by another class in the same package. Therefore i makes sense that it compiles.

In Java main function are not special in any sense. There just exists a terminal command that is able to invoke static methods called main...

like image 31
Mathias Schwarz Avatar answered Oct 01 '22 17:10

Mathias Schwarz