Home » Online Computer Education » Learn Fundamentals of Java Programming “Access Modifiers in Java Programming ” Lesson 20

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).

Java fundamentals  array  10

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).

Java fundamentals  array  11

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.

About

The main objective of this website is to provide quality study material to all students (from 1st to 12th class of any board) irrespective of their background as our motto is “Education for Everyone”. It is also a very good platform for teachers who want to share their valuable knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *