Academic Company Events NI Developer Zone Support Solutions Products & Services Contact NI MyNI

Document Type: Prentice Hall
Author: Klaus Michelsen
Book: C# Primer Plus
Copyright: 2002
ISBN: 0-672-32152-1
NI Supported: No
Publish Date: Sep 6, 2006

A Guided Tour through C#: Part I

11 ratings | 4.45 out of 5
Print

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.

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.

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.

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.



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.



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.

Buy the Book


Purchase C# Primer Plus from Prentice Hall.
11 ratings | 4.45 out of 5
Print

Reader Comments | Submit a comment »

 

Legal
Excerpt from the book published by Prentice Hall Professional (http://www.phptr.com).
Copyright Prentice Hall Inc., A Pearson Education Company, Upper Saddle River, New Jersey 07458.
This material is protected under the copyright laws of the U.S. and other countries and any uses not in conformity with the copyright laws are prohibited, including but not limited to reproduction, DOWNLOADING, duplication, adaptation and transmission or broadcast by any media, devices or processes.