Reputation: 3181
What's the difference between
class x {
//code here
}
and
public class x {
//code here
}
Sometimes I see examples on the Internet and they'll have public class
instead of class
and they're all simple programs. I use class
for my assignments and so does everybody else
Upvotes: 28
Views: 31752
Reputation: 49
The first one will be default class, i.e it cannot be accessed in any other package except itself, but can be accessed by other classes in the same package.
The second one makes it public,i.e, you can access it from any class of any package just like you access String and Array which are if different packages.
Remember, we are talking about accessible from packages not class.
Regarding, And then: If I have a class X (please capitalize the class name) that is not declared as public, can I have public instance variables (EG public String name;) in it?? ;)
Yes of course you can have public instance variables in non-public class.
Upvotes: 0
Reputation: 26492
There also exists the following visibility modifiers for members and methods and inner classes:
Upvotes: 5
Reputation: 62759
The simplest way to put it:
if everything you have is in the same package (package com.myschool.myapp at the top of every file) then there is no difference, but if anything wants to access anything outside it's package then it must be public.
For instance, "String" is in "java.lang", your package almost certainly isn't in java.lang so if string wasn't public you couldn't access it.
Upvotes: 9
Reputation: 85458
The first one will result in your class being assigned the default visibility, that is package-private
(ie: accessible within the same package
).
The second one makes it public
, that is, visible to any other class.
Upvotes: 34