Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java file with no public classes

Tags:

java

I created a class with package modifier in eclipse.

class notPublic
{
  //main() which prints a string
}

I ran this program and it was printed that string. I have a small doubt here

I read that Java compilation unit must have a public class I have a compilation unit which doesn't have public class. But It works.

What did I understand wrongly here

like image 741
Gibbs Avatar asked Jul 08 '15 17:07

Gibbs


2 Answers

The actual requirement is slightly different: every Java public class must be in a compilation unit with the name PublicClassName.java. But it's perfectly fine to have a compilation unit that does not contain a public class.

I wasn't able to find an explicit statement of this in the language specification, but the spec does seem to mention it as the preferred/recommended way of mapping Java compilation units to the filesystem.

like image 164
Sam Estep Avatar answered Sep 22 '22 00:09

Sam Estep


It works in the next way, imagine that you have a file named Dog.java with the next content:

class A{}

class B{}

class C{}

As any of the classes is public you can compile it using javac Dog.java and it is going to work.

but if one of your classes is public the name of the file must be equals to the public class, eg if you modify the last example like this : File Dog.java

public class A{}

class B{}

class C{}

And you try to compile It you are going to get "class A is public, should be declared in a file named A.java"

And for the last point you can't place all classes as public because only can have one public class per file.

like image 22
Alejandro Agapito Bautista Avatar answered Sep 21 '22 00:09

Alejandro Agapito Bautista