what is the difference between `public class` and

2019-01-31 00:43发布

I have noticed that if don't write public before a class its works same as like a public class. I can't understand why so? It should show a error when I don't declare a class as public, private or protected. But it works fine. What is the reason?

标签: java class
7条回答
Ridiculous、
2楼-- · 2019-01-31 01:21

public, protected and private are access modifiers. Public means that the subject may be accessed by any class, protected by subclass, private by the class itself, no modifier means "package protected", so the subject may be accessed by classes from the same package.

Subject is class, method, member variable.

查看更多
虎瘦雄心在
3楼-- · 2019-01-31 01:24

It works the same only because you are working with just probably one file and in the same package.

If you have more than one package then you have the problem. The class that doesn't have "public" before the name of class cannot be created in another package. You cannot use its constructor. You just cannot access it outside of the package that the class was created in.

查看更多
ら.Afraid
4楼-- · 2019-01-31 01:30

Classes are package private by default (as outlined here) so it's not behaving the same way. You just think it is because you haven't tried to consume your class from a different package.

查看更多
劫难
5楼-- · 2019-01-31 01:33

I have noticed that if don't write public before a class its works same as like a public class.

No it doesn't. Unless it's public, the class won't be visible to other code which isn't in the same package. The default accessibility (which can't be specified explicitly) is that a class (or other member) is only visible to other code within the same package.

You should read the Java Language Specification section 6.6 and the Java Tutorial (Controlling Access to Members of a Class) for more details.

查看更多
甜甜的少女心
6楼-- · 2019-01-31 01:42

There must be only one public class per .java source file and the name of the file must match with this public class.

Similar question is asked before on SO. Please find it here

查看更多
贪生不怕死
7楼-- · 2019-01-31 01:43

If you don't give an access modifier it's by default package private access. The class is not accessible outside of the package. Ideally the JLS should've included a keyword for package access to avoid confusion and unintended consequences.

Something like,

default class Student{}
查看更多
登录 后发表回答