Java Reference
In-Depth Information
You want to create members of a class that are not accessible from any other class.
Solution
Create
private
instance members rather than making them available to other classes
(
public
or
protected)
. For instance, suppose you are creating an application that
will be used to manage a team of players for a sport. You create a class named
Play-
er
that will be used to represent a player on the team. You do not want the fields for
that class to be accessible from any other class. The following code demonstrates the
declaration of some instance members, making them accessible only from within the
class in which they were defined.
private String firstName = null;
private String lastName = null;
private String position = null;
private int status = -1;
How It Works
To designate a class member as
private
, prefix its declaration or signature using the
private
keyword. The
private
access modifier is used to hide members of a class
so that outside classes cannot access them. Any members of a class that are marked as
private
will be available only to other members of the same class. Any outside class
will not be able to access fields or methods designated as
private
, and an IDE that
uses code completion will not be able to see them.
As mentioned in the solution to this recipe, there are three different access modifi-
ers that can be used when declaring members of a class. Those modifiers are
public
,
protected
, and
private
. Members that are declared as
public
are available for
any other class. Those that are declared as
protected
are available for any other
class within the same package. It is best to declare
public
or
protected
only those
class members that need to be directly accessed from another class. Hiding members of
a class using the
private
access modifier helps to enforce better object orientation.