Encapsulation not only provides a convenient way of treating an object as a single entity, but it also provides protection of the object by controlling what parts of the object are visible outside of the object.


This visibility is specifically controlled by access specifiers that define the level of visibility:

  • Public
    • Public members are accessible any place the object is visible
    • Public methods should be the only way to change an object’s attributes
    • Public members make up an object’s public interface
  • Private
    • Private members are accessible only from other members of the same class
      • i.e. once instantiated, only that object
  • Protected
    • Protected members are accessible from other members of the same class and to members of derived classes derived
      • i.e. a child class can also access the protected members of the parent


In this diagram, the red bordered otherObject only has access to the Public members of the Motorbike class. However, the derivedObject (which is intended to represent a child class of the parent class), not only has access to the Public members of the Motorbike class, but it also has access to the Protected members. The Private members of the Motorbike class remain accessible only by itself.


Generally, the default access to a class is (and should be) private, even if not explicitly stated.


Since we only want the object itself to be able to modify itself, we only allow the absolute bare minimum (that is required for the program to work) to be seen outside of the object.


All of an object’s attributes can and should only be modified by its own methods, and should therefore never be made public.


However, we make certain methods of an object public, to allow another object to invoke a change in the called object, by sending a message. The called object can then act upon that message and use its own methods to modify its attributes, thus keeping all behaviour under direct control of the messaged object itself.


Therefore, access specifiers provide protection of an object up to its public interface.


By making members Private, it forces other objects (and perhaps other programmers looking at your code) to utilise the Public methods of the object to access its attributes.



Thus allowing the interface of the class to be separated from the implementation, which is Privately taken care of inside the class, akin to a black box!

Leave a Reply