what is the difference between `public class` and just `class`?

前端 未结 8 1321
说谎
说谎 2020-12-12 18:27

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

相关标签:
8条回答
  • 2020-12-12 18:41

    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.

    0 讨论(0)
  • 2020-12-12 18:46

    No a normal class and a public class don't work the same .A class without a access modifier such as public is automatically set to default access.(No, you can't give default as access explicitly). If you create a default access class inside a package then that class cannot be accessed outside that package but public class can be accessed even outside that package

    0 讨论(0)
  • 2020-12-12 18:48

    For declarations of classes are avaible only two keywords:

    • public .Example: public class Student{//...}
    • private package(as default) .Example: class Note{//...} .It is visible only in his package.

    You can use private and protected only if you declare an member inside of a class. Example:

    public class Student{
    protected Note note;
    }
    
    0 讨论(0)
  • 2020-12-12 18:51

    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.

    0 讨论(0)
  • 2020-12-12 18:56

    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

    0 讨论(0)
  • 2020-12-12 19:01

    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.

    0 讨论(0)
提交回复
热议问题