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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With