Problem

3/6

Access Modifiers

Theory Click to read/hide

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.

Problem

Make all fields of the Book class private. Remove any methods it currently has.

Create a public method named setText (return type void) with one argument newText that will change the value of text to newText. Add a private getWordsCount method that will count the number of words in the text and return it as int.
The word — a sequence of any characters, among which there is no space.

It is guaranteed that several spaces in a row cannot go.