In java, do we really have to do that in order our variable or method to be public? For example:
void aaa() {
...
}
or
public void aaa() {
...
}
If it is a must, why?
In java, do we really have to do that in order our variable or method to be public? For example:
void aaa() {
...
}
or
public void aaa() {
...
}
If it is a must, why?
Well that's not a variable, that's a method - but yes, you have to do that to make a method public. If you don't, it has the default package access, and won't be accessible from other packages. You should judge for yourself whether any particular method you write should be accessible only within the same class (make it private
) to subclasses (make it protected
), to the package (leave the default; you can't state package access explicitly, unfortunately) or to everything (make it public
).
(This is a slight simplification of the access modifiers, but it's a start.)
As for why this is the case - typically you should limit visibility so that your type only exposes the methods which really make sense for the concept it's trying to encapsulate. You may have many more private methods which are implementation-specific, and which the outside world shouldn't know or care about.
You can ommmit access level modifier anywhere except near main method. There it must be set to public.
Not putting a modifier is actually different than public
, private
, or protected
.
With no modifier, only the class itself and any class in the same package can access the attribute.
Learn more here: In Java, difference between default, public, protected, and private
The two methods are different: the first has package visibility, while the second one is public.
The difference is that package-visible methods appear public only to methods inside the same package, while public methods are visible to all methods, inside and outside the package.
So the answer to your question depends on your intent: if your method is truly part of your component's interface, make it private; if it is designed for use only inside the package, keep it at the default package visibility.
In your first example, the method will be package scoped -- i.e. only things in the same package can use it. So yes, you do need to declare public fields/methods/classes as such, otherwise they will have package scope.
The default is package private.
If you want public or anything else, you must specify it.
Method can be accessed by the class itself, other classes within the same package, but not outside of the package, and not by sub-classes.
See chart at bottom:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html