Java Access Specifiers
The Java access specifiers are,
- public
- private
- protected
You will visit Java access
specifiers public, protected, and private
for each method and member in
your class. Each access specifier controls the access for only that particular definition.
One way or another, everything
has some kind of access specified for it. In the following sections, you’ll
learn all about the various types of access, starting with the default access.
public
When you use the public keyword,
it means that the member that declared as public is available to everyone, i.e.
member variable or function that is declared as public, can be accessed from
anywhere in the application. It can be accessed from different package also.
private
The private keyword means that no
one can access that member except that particular class, inside methods of that
class. Other classes in the same package cannot access private members. On the
other hand, private variable in the method can be accessed from other method or
even class if the method that contain private variable is public.
protected
protected
methods and fields can only be accessed within the same package to which the
methods and fields belongs,, but not from anywhere else. You use the protected
access level when it is appropriate
to require method or field access within same package, but not for
unrelated classes.
For
Example,
public
class Square { // public class
private double x, y // private (encapsulated) instance variables
public setCorner(int x, int y) { // setting values of private fields
this.x = x;
this.y = y;
}
public getCorner() { // setting values of private fields
return Point(x, y);
}
}
Java Packages
A
package is what you use to get entire library using import keyword, such as,
import
java.util.*;
This
brings in the entire utility library that’s part of the standard Java
distribution. Since, for example, the class ArrayList is in java.util, you can
now either specify the full name java.util.ArrayList.
i.e.,
if you want to import a single class, you can name that class in the import
statement like,
import
java.util.ArrayList;
package
can also created by programmer, to remove ambiguity in the programmer. If
programmer wants to arrange classes modules wise, then he can make different
packages for each module and can make low ambiguous application. In practical
manner, if more than on programmers are working upon an application, then, if
same class name given by two programmers that are working upon different module,
then it will not conflict each other. So, in this way, packaging is organizing
the application.
.thank you for sharing useful post.
ReplyDeletejava programming tutorial
welookups
online coding for kids Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info.
ReplyDelete