Hiding Details and Creating the Public Interface

Learn about the different concepts of data hiding in object-oriented programming.

The key purpose of modeling an object in object-oriented design is to determine what the public interface of that object will be. The interface is the collection of attributes and methods that other objects can access to interact with that object. Other objects do not need, and in some languages are not allowed, to access the internal workings of the object.

Example

A common real-world example is television. Our interface to the television is the remote control. Each button on the remote control represents a method that can be called on the television object. When we, as the calling object, access these methods, we do not know or care if the television is getting its signal from a cable connection, a satellite dish, or an internet-enabled device. We don’t care what electronic signals are being sent to adjust the volume or whether the sound is destined for speakers or headphones. If we open the television to access its internal workings, for example, to split the output signal to both external speakers and a set of headphones, we may void the warranty.

Encapsulation and information hiding

This process of hiding the implementation of an object is suitably called information hiding. It is also sometimes referred to as encapsulation, but encapsulation is actually a more encompassing term. Encapsulated data is not necessarily hidden. Encapsulation is, literally, creating a capsule (or wrapper) on the attributes and methods to present a simpler view to the user. Whereas data hiding restricts data usage to assure the security of the data. The TV’s external case encapsulates the state and behavior of the television. We have access to the external screen, the speakers, and the remote. We don’t have direct access to the wiring of the amplifiers or receivers within the TV’s case.

Get hands-on with 1200+ tech skills courses.