Learn Fundamentals of Java Programming “Access Modifiers in Java Programming ” Lesson 20
Access Modifiers
In the previous section, we allowed access to the data members of the class from outside the class. We created Book objects in the BookTest class and were able to set the object’s data members. However, it is generally not good programming practice to allow data members to be accessed outside the class. By allowing objects to change their data members arbitrarily, we lose control over the values being held in them. This makes debugging code harder and our code vulnerable to security issues. To make a data member or a method member of a class visible only within the class, we add the keyword private before its declaration (Figure 1.8g).
Private members of a class cannot be accessed outside the class. Declaring the data members of the Book class private, we won’t be allowed access to them in the BookTest class (Figure 1.8h).
As opposed to private, a public member of the class has visibility both within and outside the class. By default, all members of a class are public.