Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

class

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?

like image 997
Tushar Monirul Avatar asked May 27 '13 19:05

Tushar Monirul


People also ask

What does public class mean?

In object-oriented programming, a public class is any part of the program that accesses or updates its members using the member name to be accessed. This type of class is useful for information or methods that need to be available in any part of the program code. Class, Private, Programming terms.

What is the difference between public class and class?

A public class has "public" visibility, which means that it is accessible to any class in any package, while a class has "default" or "package" visibility, i.e. the class is accessible only to classes inside the same package. Also if you are working only on one package then there is no difference, you can use both.

What is the difference between a public and a non public class?

A public class will have access specifier "public" and its members can be accessed with in and out of the class in which they are specified. A class which doesnt have the public access specifier are called as non-public classes and its member can be accessed only within the class in which they are specified.


1 Answers

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.

like image 175
Jon Skeet Avatar answered Oct 11 '22 15:10

Jon Skeet