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
The first one will result in your class being assigned the default visibility, that is
package-private
(ie: accessible within the samepackage
).The second one makes it
public
, that is, visible to any other class.Reference: Controlling Access to Members of a Class
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.
There also exists the following visibility modifiers for members and methods and inner classes:
itself.
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.