Most instance-variable declarations are preceded with the keyword private
(as in line 7). Like public
, keyword private is an access modifier. Variables or methods declared with access modifier private are accessible only to methods of the class in which they’re declared. Thus, variable courseName
can be used only in methods setCourseName
, getCourseName
and displayMessage
of (every object of) class GradeBook
.
Declaring instance variables with access modifier private
is known as data hiding or information hiding. When a program creates (instantiates) an object of class GradeBook
, variable courseName
is encapsulated (hidden) in the object and can be accessed only by methods of the object’s class. This prevents courseName
from being modified accidentally by a class in another part of the program. In class GradeBook
, methods setCourseName
and getCourseName
manipulate the instance variable courseName
.