Access modifiers
By default, all
fieldsand
methods of a class in Java are
private. This means that no one can access them, which means that outside the objects of this class, no method can use the fields and methods of objects of this class.
Fields and methods can be made public with the
access modifier public
. There is also a
private
modifier that makes the field private. It is optional as all fields and methods are private by default. Here is an example of using the
public
and
private
modifiers.
class Book
{
public Stringname;
String authorName;
private int ageRequirement;
Stringtext;
public int pageCount;
int getTextLength()
{
return text length();
}
public int getAverageLetterCount()
{
return getTextLength() / pageCount;
}
private int getDifficuiltyLevel()
{
return 5 * ageRequirement * text.Length();
}
}
In this version of the Book
class, the fields name
and pageCount
are made public for reading and modification in other objects. The getAverageLetterCount()
method is also available to be called from objects of other classes. All other fields and methods remain private and are available only in the methods of this class. In the public method getAverageLetterCount()
we can call the private method getTextLength()
because getAverageLetterCount()
belongs to the class itself. But it won't work from a method of another class.
But why then make the fields private? In Java code, you will mostly only see private fields. The fact is that if access to private fields is carried out through the public methods of the object, then with any such access to private fields it will be possible to perform additional actions and checks. More about this will be in the lesson about encapsulation.