Home > Articles

0672321521

  • Print
  • + Share This

Abstraction and Encapsulation

Object-oriented programming is at the core of C#. Practically speaking, everything in C# is an object. Even the simple program you encountered in Chapter 2, "Your First C# Program" relies on OO principles. So before we dive into the first C# example, it is useful to expand on our OO introduction by looking at two core concepts of OO called abstraction and encapsulation.

Abstraction

Consider an airplane. Initially, it seems an impossible task to represent an airplane in a computer program. Just think about all the details—intricately designed jet engines, extremely complex onboard computers, entertainment systems. It is dizzying. However, by looking at the role we want the airplane to play in our application, we can significantly reduce the features to be represented. Perhaps we just need an airplane to be a position on a map. Perhaps we need to test the aerodynamic characteristics of an airplane in which case we only need to represent its outer shape. Perhaps an interior designer is making a 3D presentation of the airplane's interiors, in which case, he needs to represent only the interior surfaces of the airplane.

In every airplane role mentioned, it is possible to identify the key characteristics of the airplane relevant to that particular application. Essentially, we are coping with the intricacies of the airplane by abstracting away from them.

Abstraction is one of the fundamental concepts utilized by programmers to cope with complexity.

When an object (or system) is specified or depicted in a simpler, less detailed fashion than its real counterpart, this specification is called an abstraction. Highlighting the properties that are relevant to the problem at hand, while ignoring the irrelevant and unduly complicating properties, creates a useful abstraction in OOP.

When creating an abstraction, it is important to include only the features that are part of the object being specified. The behavior of an object must not go beyond that of the expected. For example, creating an abstract car with the ability to draw architectural plans should be avoided. It creates confusion among yourself and other programmers trying to understand your source code.

NOTE

Recall the elevator simulation discussion from Chapter 2, "Your First C# Program." When designing an elevator simulation program, we must first ignore (by abstraction) all the unnecessary characteristics and parameters of the real world. For example, the color of each elevator and the hairstyle of each person in them can be disregarded. On the other hand, important information is the speed of each elevator, the number of people wanting to catch an elevator, and the floors to which they want to travel.

The simulation enables us to calculate statistics concerning waiting times and eventually an estimate for the number and types of elevators needed to service the building, just as Big Finance Ltd. requested in Chapter 2.

You have already seen one example of an abstraction in the C# program example in Chapter 2. It contained a class called Shakespeare.

Lacking arms, legs, inner organs, and a brain, the class had very little resemblance to the writer and person named Shakespeare, but it could still recite one very short quote of Shakespeare. Thus, because a very tiny piece of Shakespeare could be found in it, we still dared to call our class Shakespeare. Our Shakespeare class was an abstraction of the real writer and person—Shakespeare.

Encapsulation

Whereas abstraction focuses on reducing the complexity of how we view the real world, encapsulation concentrates on the design of our C# source code. It is a powerful mechanism for reducing complexity and protecting data of individual objects on the programming level.

Encapsulation is the process of combining data and the actions (methods) acting on the data into a single entity, just as you saw in Chapter 2. In OOP and hence C#, such an entity is equivalent to an object.

Encapsulation is a mechanism for hiding instance variables and irrelevant methods of a class from other objects. Only methods, which are necessary to use an object of the class, are exposed.

The term encapsulation might sound like a sophisticated academic term, but despite this first impression, we can find parallels to it from our everyday life. We might not refer to it as encapsulation, but the analogies are so striking that an example from the real world might be instructive. The example provided here returns to the world of elevators.

Encapsulation in a Real World Elevator System

Any useful elevator has a mechanism, such as buttons, that allow a passenger to select his or her destination floor. Pressing a button is a very easy action to perform for the user of the elevator. However, for the elevator faced with many conflicting simultaneous requests from many different people, it can be a complicated matter deciding which floor to go to and fulfill the request of each traveler expediently. Many conditions complicate the design of an elevator; some examples are provided in the following Note.

The Complicated Life of an Elevator

Modern elevators rely on sophisticated algorithms residing inside computers that control every move they make. Here are a few reasons why it is a complicated matter to decide the next move of an elevator.

A person called A might enter the elevator at floor 3 and request to go to floor 30. However, another person, B, has already pressed the button on floor 1 requesting to be picked up there. If the elevator goes directly to floor 30 with person A (but without B), person A will get there as fast as he or she could ever expect. However, person B has to wait. Perhaps, by merely moving two floors down, the elevator could have taken both people to a higher floor at the same time, saving time and power. Instead, the elevator has to go all the way up to floor 30 and then back down to pick up B. With many people constantly requesting elevators and destination floors, the matter gets much more complex.

At least a couple of other aspects complicate matters further for our trusted elevator:

  • Several elevators are probably working together to transport people between the different floors. They consequently need a "team" approach to fulfill as many requests as possible. Densely populated buildings with large amounts of traffic between floors require approximately two elevators for every three floors. Thus, a 60-floor building would require about 40 elevators.

  • Certain floors are more likely to be visited and have pick-me-up requests than other floors. These probabilities might vary throughout the day. If the elevators can somehow remember these patterns, they can optimize the efficiency of the sequence of floors visited.

Sophisticated algorithms have been constructed running inside computers that control the movements of the elevators, allowing them to serve as many people as possible, fast and efficiently.

This was a bit of elevator talk, but it leads us to an essential observation.

It is easy for a person to press a button and thereby use the hidden complex services (algorithms, engines, hydraulics, gears, wires, data about current speed, maximum speed, and so on) provided by the elevator. Thus, the ignorant passenger, in terms of elevator technology, can easily utilize the services of the elevator to accomplish his or her tasks of the day.

Not only is this concealment of elevator data, algorithms, and mechanics an advantage for travelers who do not want to deal with complex matters that are irrelevant to them; but it also improves the reliability of the elevator itself. No unauthorized and incompetent person can gain access to the inner control mechanisms of the elevator. Imagine if the elevator was equipped with a small "cockpit" where anybody traveling in the elevator could tinker with the maximum speed, or make the elevator believe it was on an incorrect floor, or force it to move to a floor other than the one calculated by its control algorithms. A chaotic situation would soon prevail.

A final advantage of segregating the buttons from the underlying elevator mechanisms is the capability of making changes to these mechanisms without altering the buttons and, hence, the way it is operated. In this way, an elevator can contain the same buttons that everyone has become accustomed to using for many years, while many underlying hardware and software upgrades have taken place to keep the system up to date.

Encapsulation in an Elevator Simulation

Let's look at how the previously discussed issues relate to an object-oriented C# elevator simulation program.

An elevator simulation program written in C# will probably have Elevator and Person objects along with others. Even though now inside a computer program, a Person object will still be able to perform the equivalent of "pressing the button" of an Elevator object and giving it a floor request.

Each Elevator object of the simulation probably contains, like its real counterpart, many complex methods and many sensitive data. For example, many Elevator objects might, to make the simulation particularly realistic, be equipped with algorithms (similar to the algorithms of real world elevators) to calculate the most efficient sequence of floors visited.

Now the important analogy—each Person object (and the programmer implementing it) of the simulation should still not need or be allowed to "know" about the inner complexities (source code) of any Elevator object. All they should "care" about, just like their real counterparts, is to get from one floor to another. They don't want to be confused about unnecessary complexities either. They should not be allowed to tinker with the inner workings (data and source code) of the Elevator object, and the programmers implementing the elevator should be able to change and upgrade the source code without interfering with how the Elevator object is used (operated).

To accomplish this concealment in the OO world, we say that we encapsulate (hide) the underlying data and source code that is irrelevant for all but the Elevator objects themselves.

When we write and create the Elevator objects in C#, we somehow need a way to tell the program and the other objects, including the Person objects, that the data and source code are hidden. C# has a special word for this purpose called private. Thus, by declaring the data and relevant source code to be private, we are able to prevent any other object from gaining access to these parts of our Elevator object.

Convention

Any words with a special meaning in C# as well as references made to parts of source code presented in this book appear in a special font, such as private.

private and public

The word private has a special meaning to the C# compiler. It is used to hide method and instance variables (residing inside an object) from other objects.

Likewise, the word public has a special (albeit opposing) meaning to the C# compiler. public is used to allow other objects access to methods and instance variables of a specific object.

Because private and public control the accessibility of the methods and instance variables belonging to an object, these two words are referred to as access modifiers.

However, if we hide all the instance variables and methods of an object, none of its methods can be accessed, rendering the object completely useless. For example, a Person object needs somehow the ability to "express" its floor request. A method with this capacity could arbitrarily be called NewFloorRequest. What would happen if we declared NewFloorRequest to be private? Well, an Elevator object that had just "loaded" a "passenger" (a Person object) with these characteristics would not be able to access the NewFloorRequest method, which is the only means to find out the floor to which this "passenger" "wanted" to "travel." This would be the equivalent of a real person without any arms, who is unable to reach out and press a button. In the C# source code, we somehow need a way to put "arms" on our Person object and buttons on our Elevator object, so contact can be made between the two objects.

We do this by exposing methods like NewFloorRequest. Instead of marking this method with the private word, we use another special word from C# called public.

A Person object can now "walk into" an Elevator object. When ready, the Elevator object can send a message to the Person object and, via the NewFloorRequest method, receive the desired destination floor of this Person. Figure 3.1 illustrates this scenario. Notice the double lined arrow. It represents the message sent to the Person object. The single lined arrow going in the opposite direction represents the value (the floor number request) returned to the Elevator object from the Person object. The double lined arrow represents a method call. Programmers say that the Elevator object is calling the NewFloorRequest method.

The Elevator object, like its real counterpart, might need to somehow keep track of, for example, the speed at which it is traveling and its maximum speed; these are the instance variables (data) of the object, as mentioned previously. Just like the elevators of the real world, the Elevator objects of the C# simulation do not want any interference from other objects to mistakenly change their instance variables. Therefore, the Elevator objects declare them to be private, as shown in Figure 3.1, making them inaccessible for other objects.

Encapsulation in a Typical Class

Recall the objects displayed in Figure 2.3 of Chapter 2. They are equivalent to the objects shown in Figure 3.1. A generalized object using C#'s access modifiers and indicating the encapsulating public layer is displayed in Figure 3.2. Notice how the public area of this generic object can be viewed to surround the private area like a protective shell. The object still contains the instructions executed by the computer (flow of execution or algorithms); they have now been divided into a public part and a private part. All the data (or instance variables) are hidden inside in the private area.

Figure 3.1 Elevator object requesting information from Person object.

Figure 3.2 A generic object.

Class and Object

The class works as a template for the creation of objects. The blueprint of an elevator is to the elevator designer what the class is to the programmer.

All objects of the same class contain the same methods and the same instance variables. Consequently, a class is a logical construct; but an object has the ability to perform the actions specified by the class.

All objects of the same class are called instances of a class. When an object is formed during the execution of a program (as when a tangible elevator is manufactured), we say it is created or instantiated.

We can now depict a typical generic class as illustrated in Figure 3.3. Simply viewed, the class consists of data (instance variables) and algorithms (methods). When you write the source code for a class, you specify the methods and the instance variables that you want this class, and all objects derived from it, to contain. All instance variables and methods are collectively referred to as members or fields of the class.

Figure 3.3 A generic class illustrates encapsulation.

Encapsulation entails a layer that is meant to communicate with the outside world. Only through this part can the outside world communicate with the object. It further allows for a hidden part to exist inside this layer. This protective layer is denoted an interface and should only consist of methods.

Helper Methods

private methods can only be called by methods belonging to that same object. They provide functionality and support for other (often public) methods in the object and are frequently called helper methods or utility methods.

NOTE

The main advantages of encapsulation are as follows:

  • It provides for an abstraction layer—Encapsulation saves the programmer who uses a class the need to know about the details of how this particular class is implemented.

  • It decouples the user interface of the object with its implementation—It is possible to upgrade the implementation of an object while maintaining its user interface.

  • It covers the object with a protective wrapper—Encapsulation protects the data inside the object from unwanted access that, otherwise, could cause the data to be corrupted and misused.

Only Methods Should Be Part of an Object's Interface, not Instance Variables

Instance variables positioned in the interface (this is possible in C#) effectively break the protective wrapper and allow for other objects to tinker with those exposed pieces of data. If access to specific data is needed, it should always be through a method (or properties and indexers, as discussed in later chapters).

A Note on Learning Object-Oriented Programming

Object-oriented programming and its related concepts might seem a bit fuzzy and overwhelming to you right now. This is perfectly normal, so don't despair.

In my experience, learning OOP is not like learning the content of, say, a history book by heart. While reading the history book, you gradually learn the material. It seems that an hour spent studying gives you an hour's worth of knowledge (unless the subject is complex and interrelated with other historical events), resulting in a nearly linear relationship between the amount of hours spent studying and the amount of knowledge you have acquired (see Figure 3.4).

Figure 3.4 Comparing learning by heart and learning OOP.

This is most often not the case when learning OOP because of its interrelated and dynamic aspects and because OOP implies more than just a bunch of statements being executed one after the other. Initially, you will likely learn the names of several concepts (see 1 in Figure 3.4) but without much understanding for their real purpose. You might spend some time in this fuzzy, perhaps frustrating stage. Despite your studying efforts, you might not feel you are really gaining an increased understanding for the underlying logic; new concepts presented seem to confuse rather than enlighten (see 2 in Figure 3.4). However, your mind is constantly absorbing new aspects, information, and subtleties whenever you read the theory and work through the examples. Suddenly, at a specific moment in time (perhaps at night just after waking up from your favorite dream about abstraction and encapsulation), you experience this quantum leap in understanding, this AHA! Experience. All of a sudden, the pieces of the puzzle form a meaningful picture (see 3 in Figure 3.4). Equipped with this fundamental understanding, it becomes much easier to learn the new, more advanced OOP concepts (see 4 in Figure 3.4).

So don't get frustrated—have fun instead. Attack the OOP concepts from different angles, theoretically as well as experimentally, with the C# language.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020